How can I get a list of all mounted filesystems in Java on Unix?

后端 未结 6 1038
误落风尘
误落风尘 2020-12-10 19:38

I\'m running Java on a Unix platform. How can I get a list of all mounted filesystems via the Java 1.6 API?

I\'ve tried File.listRoots() but that return

6条回答
  •  温柔的废话
    2020-12-10 20:01

    You can call the getmntent function (use "man getmntent" to get more information) using JNA.

    Here is some example code to get you started:

    import java.util.Arrays;
    import java.util.List;
    
    import com.sun.jna.Library;
    import com.sun.jna.Native;
    import com.sun.jna.Pointer;
    import com.sun.jna.Structure;
    
    public class MntPointTest {
        public static class mntent extends Structure {
            public String mnt_fsname; //Device or server for filesystem
            public String mnt_dir; //Directory mounted on
            public String mnt_type; //Type of filesystem: ufs, nfs, etc.
            public String mnt_opts;
            public int mnt_freq;
            public int mnt_passno;
    
            @Override
            protected List getFieldOrder() {
                return Arrays.asList("mnt_fsname", "mnt_dir", "mnt_type", "mnt_opts", "mnt_freq", "mnt_passno");
            }
        }
    
        public interface CLib extends Library {
            CLib INSTANCE = (CLib) Native.loadLibrary("c", CLib.class);
    
            Pointer setmntent(String file, String mode);
            mntent getmntent(Pointer stream);
            int endmntent(Pointer stream);
        }
    
        public static void main(String[] args) {
            mntent mntEnt;
            Pointer stream = CLib.INSTANCE.setmntent("/etc/mtab", "r");
            while ((mntEnt = CLib.INSTANCE.getmntent(stream)) != null) {
                System.out.println("Mounted from: " + mntEnt.mnt_fsname);
                System.out.println("Mounted on: " + mntEnt.mnt_dir);
                System.out.println("File system type: " + mntEnt.mnt_type);
                System.out.println("-------------------------------");
            }
    
            CLib.INSTANCE.endmntent(stream);
        }
    }
    

提交回复
热议问题