4

UnixプラットフォームでJavaを実行しています。Java 1.6 APIを介してマウントされたすべてのファイルシステムのリストを取得するにはどうすればよいですか?

試しましFile.listRoots()たが、単一のファイルシステム(つまり、/)が返されます。私が使用する場合、df -h私はそれ以上のものを見ます:

Filesystem      Size   Used  Avail Capacity   iused     ifree %iused  Mounted on
/dev/disk0s2   931Gi  843Gi   87Gi    91% 221142498  22838244   91%   /
devfs          187Ki  187Ki    0Bi   100%       646         0  100%   /dev
map -hosts       0Bi    0Bi    0Bi   100%         0         0  100%   /net
map auto_home    0Bi    0Bi    0Bi   100%         0         0  100%   /home
/dev/disk1s2   1.8Ti  926Gi  937Gi    50% 242689949 245596503   50%   /Volumes/MyBook
/dev/disk2     1.0Gi  125Mi  875Mi    13%     32014    223984   13%   /Volumes/Google Earth

/home私も(少なくとも)見ることを期待します。

4

6 に答える 6

17

Java7 +では、nioを使用できます

import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.FileSystems;

public class ListMountedVolumesWithNio {
   public static void main(String[] args) throws IOException {
      for (FileStore store : FileSystems.getDefault().getFileStores()) {
         long total = store.getTotalSpace() / 1024;
         long used = (store.getTotalSpace() - store.getUnallocatedSpace()) / 1024;
         long avail = store.getUsableSpace() / 1024;
         System.out.format("%-20s %12d %12d %12d%n", store, total, used, avail);
      }
   }
}
于 2014-10-30T10:18:04.110 に答える
5

Javaはマウントポイントへのアクセスを提供しません。mountを介してシステムコマンドを実行しRuntime.exec()、その出力を解析する必要があります。それか、の内容を解析し/etc/mtabます。

于 2013-01-21T00:27:02.820 に答える
4

OSHI(Java用のオペレーティングシステムおよびハードウェア情報ライブラリ)は、 https://github.com/oshi/oshiで役立ちます。

このコードをチェックしてください:

@Test
public void test() {

    final SystemInfo systemInfo = new SystemInfo();
    final OSFileStore[] fileStores = systemInfo.getOperatingSystem().getFileSystem().getFileStores();
    Stream.of(fileStores)
    .peek(fs ->{
        System.out.println("name: "+fs.getName());
        System.out.println("type: "+fs.getType() );
        System.out.println("str: "+fs.toString() );
        System.out.println("mount: "+fs.getMount());
        System.out.println("...");
    }).count();

}
于 2020-02-20T13:33:43.887 に答える
3

問題を解決するには、次の方法を使用してみてください。

私のコード

public List<String> getHDDPartitions() {
    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/mounts"), "UTF-8"));
        String response;
        StringBuilder stringBuilder = new StringBuilder();
        while ((response = bufferedReader.readLine()) != null) {
            stringBuilder.append(response.replaceAll(" +", "\t") + "\n");
        }
        bufferedReader.close();
        return Lists.newArrayList(Arrays.asList(stringBuilder.toString().split("\n")));
    } catch (IOException e) {
        LOGGER.error("{}", ExceptionWriter.INSTANCE.getStackTrace(e));
    }
    return null;
}

public List<Map<String, String>> getMapMounts() {
    List<Map<String, String>> resultList = Lists.newArrayList();
    for (String mountPoint : getHDDPartitions()) {
        Map<String, String> result = Maps.newHashMap();
        String[] mount = mountPoint.split("\t");
        result.put("FileSystem", mount[2]);
        result.put("MountPoint", mount[1]);
        result.put("Permissions", mount[3]);
        result.put("User", mount[4]);
        result.put("Group", mount[5]);
        result.put("Total", String.valueOf(new File(mount[1]).getTotalSpace()));
        result.put("Free", String.valueOf(new File(mount[1]).getFreeSpace()));
        result.put("Used", String.valueOf(new File(mount[1]).getTotalSpace() - new File(mount[1]).getFreeSpace()));
        result.put("Free Percent", String.valueOf(getFreeSpacePercent(new File(mount[1]).getTotalSpace(), new File(mount[1]).getFreeSpace())));
        resultList.add(result);
    }
    return resultList;
}

private Integer getFreeSpacePercent(long total, long free) {
    Double result = (Double.longBitsToDouble(free) / Double.longBitsToDouble(total)) * 100;
    return result.intValue();
}
于 2013-09-13T05:31:32.717 に答える
1

JNAを使用してgetmntent関数を呼び出すことができます(詳細については、「mangetmntent」を使用してください)。

開始するためのサンプルコードを次に示します。

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);
    }
}
于 2014-01-31T12:18:58.167 に答える
0

mount@Cozzamaraがそれが進むべき道であると指摘したとき、私はすでに使用する途中でした。私が最終的に得たのは:

    // 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<File> roots = new ArrayList<File> ();
    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 <filesystem> (...)"; 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 ();
于 2013-01-21T00:36:33.567 に答える