gpt4 book ai didi

java - 如何使用Java读取Unix目录中的文件?

转载 作者:行者123 更新时间:2023-12-01 14:32:04 25 4
gpt4 key购买 nike

我在 unix 目录中有一个文件,我需要读取它并将其内容显示到页面上。我在我的 java 代码中使用 jcraft 库。我能够连接到 Unix 服务器并找到该文件,但无法读取它。我找到了读取文件的示例代码,但它不起作用,它死在 int c = in.read() 行上,可能卡在循环中......我发布我的代码也许你可以发现问题。如果有其他(更好)的方法可以做到这一点,我将不胜感激一个例子。希望我的问题和示例代码足够清楚。谢谢大家。

public String readFile(String path) throws Exception {

ChannelExec c = (ChannelExec)session.openChannel("exec");
OutputStream os = c.getOutputStream();
InputStream is = c.getInputStream();
c.setCommand("scp -f " + path); //path is something like /home/username/sample.txt
c.connect();
String header = readLine(is);

int length = Integer.parseInt(header.substring(6, header.indexOf(' ', 6)));
os.write(0);
os.flush();

byte[] buffer = new byte[length];
length = is.read(buffer, 0, buffer.length);
os.write(0);
os.flush();

c.disconnect();

return new String(buffer);
}

private String readLine(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (;;) {
int c = in.read(); // code stops working here
if (c == '\n') {
return baos.toString();
} else if (c == -1) {
throw new IOException("End of stream");
} else {
baos.write(c);
}
}
}

最佳答案

您想考虑使用 ChannelSftp 而不是 ChannelExec:

ChannelSftp channelSftp = null;
try {
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
is = channelSftp.get(path);
// read the contents, etc...
} finally {
if (channelSftp != null) {
channelSftp.exit();
}
}

关于java - 如何使用Java读取Unix目录中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16797340/

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