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

后端 未结 6 1089
误落风尘
误落风尘 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 20:01

    I was already on the way to using mount when @Cozzamara pointed out that's the way to go. What I ended up with is:

        // get the list of mounted filesystems
        // Note: this is Unix specific, as it requires the "mount" command
        Process mountProcess = Runtime.getRuntime ().exec ( "mount" );
        BufferedReader mountOutput = new BufferedReader ( new InputStreamReader ( mountProcess.getInputStream () ) );
        List roots = new ArrayList ();
        while ( true ) {
    
            // fetch the next line of output from the "mount" command
            String line = mountOutput.readLine ();
            if ( line == null )
                break;
    
            // the line will be formatted as "... on  (...)"; get the substring we need
            int indexStart = line.indexOf ( " on /" );
            int indexEnd = line.indexOf ( " ", indexStart );
            roots.add ( new File ( line.substring ( indexStart + 4, indexEnd - 1 ) ) );
        }
        mountOutput.close ();
    

提交回复
热议问题