gpt4 book ai didi

java - 在 java 中列出 ubuntu 上的附加设备

转载 作者:太空宇宙 更新时间:2023-11-04 12:29:39 26 4
gpt4 key购买 nike

我有点难过,目前我正在尝试通过一个小型 java 应用程序(类似于 gparted)在 linux 中列出我系统上的所有连接设备,我的最终目标是获得路径到设备,以便我可以在我的应用程序中对其进行格式化并执行其他操作,例如标签、分区等。

我目前有以下返回“系统根目录”,它在 Windows 上将获得适当的驱动器(例如:“C:/D:/...”)但在 Linux 上它返回“/”,因为这是它的技术根。我希望在数组中获取设备的路径(例如:“/dev/sda/dev/sdb ...”)。

我现在用的是什么

import java.io.File;

class ListAttachedDevices{
public static void main(String[] args) {
File[] paths;

paths = File.listRoots();

for(File path:paths) {
System.out.println(path);
}
}
}

非常感谢任何帮助或指导,我对 SO 比较陌生,我希望这些信息足以涵盖所有内容。

提前感谢您的任何帮助/批评!

编辑:

根据 Phillip 的部分建议,我已将我的代码更新为以下内容,我现在遇到的唯一问题是检测所选文件是否与 linux 安装(执行操作不安全)或附加驱动器(安全执行操作)

import java.io.File;
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import javax.swing.filechooser.FileSystemView;

class ListAttachedDevices{
public static void main(String[] args) throws IOException {
ArrayList<File> dev = new ArrayList<File>();

for (FileStore store : FileSystems.getDefault().getFileStores()) {

String text = store.toString();
String match = "(";
int position = text.indexOf(match);

if(text.substring(position, position + 5).equals("(/dev")){
if(text.substring(position, position + 7).equals("(/dev/s")){
String drivePath = text.substring( position + 1, text.length() - 1);
File drive = new File(drivePath);
dev.add(drive);

FileSystemView fsv = FileSystemView.getFileSystemView();

System.out.println("is (" + drive.getAbsolutePath() + ") root: " + fsv.isFileSystemRoot(drive));
}
}
}
}
}

编辑 2:

忽略之前的编辑,我没有意识到这没有检测到尚未格式化的驱动器

最佳答案

正在关注 Elliott Frisch's使用/proc/partitions 的建议我想出了以下答案。 (请注意,这还会列出可引导/系统驱动器)

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

class ListAttachedDevices{
public static void main(String[] args) throws IOException {
ArrayList<File> drives = new ArrayList<File>();
BufferedReader br = new BufferedReader(new FileReader("/proc/partitions"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();

while (line != null) {
String text = line;
String drivePath;

if(text.contains("sd")){
int position = text.indexOf("sd");
drivePath = "/dev/" + text.substring(position);
File drive = new File(drivePath);
drives.add(drive);
System.out.println(drive.getAbsolutePath());
}

line = br.readLine();
}
} catch(IOException e){
Logger.getLogger(ListAttachedDevices.class.getName()).log(Level.SEVERE, null, e);
}
finally {
br.close();
}
}
}

关于java - 在 java 中列出 ubuntu 上的附加设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43636943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com