开发环境(win)及生产环境(linux) 俩个操作linux命令
自己写的获取文件大小太慢 就直接通过操作系统来获取
实在是自己写的遍历方法在文件太多的时候获取大小太慢了
安装jsch依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
测试代码 这个只支持在任何情况下
传入参数 command: 你需要执行的命令 例如 cd /home
public double getDev(String command){
String host = "ip";
int port = 22;//端口
String username = "root";//账号
String password = "password";//密码
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] buffer = new byte[1024];
StringBuilder output = new StringBuilder();
// 以下是我对linux的输出信息进行操作
while (true) {
while (in.available() > 0) {
int bytesRead = in.read(buffer);
output.append(new String(buffer, 0, bytesRead));
}
if (channel.isClosed()) {
if (in.available() > 0) continue;
break;
}
}
List<String> fileList = new ArrayList<>();
String[] lines = output.toString().split("\t");
int i = 0;
for (String line : lines) {
String[] parts = line.split("\n");
String fileName;
if (i == 0) {
fileName = parts[0];
} else {
try {
fileName = parts[1];
} catch (Exception e) {
fileName = "0";
}
}
i++;
fileList.add(fileName);
}
channel.disconnect();
session.disconnect();
return fileList.stream()
.mapToDouble(Double::parseDouble)
.sum();
} catch (JSchException | IOException e) {
e.printStackTrace();
}
return 0;
}
在本机linux下
directory: 这个参数做其他操作可以不用 但是我获取文件大小必须用他 因为本机不支持直接cd
public double fetch(String directory){
try{
// Run the Linux command
String command = "du -sh ./* -b";
// Create ProcessBuilder and set the working directory
ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", command);
processBuilder.directory(new File(directory));
processBuilder.redirectErrorStream(true);
// Start the process
Process process = processBuilder.start();
// Read the output
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
List<String> fileList = new ArrayList<>();
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
String[] parts = line.split("\t");
String fileName;
if (i == 0) {
fileName = parts[0];
} else {
try {
fileName = parts[0];
} catch (Exception e) {
fileName = "0";
}
}
i++;
fileList.add(fileName);
}
System.out.println(fileList);
return fileList.stream()
.mapToDouble(Double::parseDouble)
.sum();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}