如何使用Java在Unix目录中读取文件?

时间:2013-05-28 16:45:54

标签: java unix jsch

我在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);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您希望使用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();
    }
}

答案 1 :(得分:0)

这看起来不错。我假设它只是挂起(就像你说的那样)。

  

[...]此方法将阻塞,直到输入数据可用[...]

我在想你在建立频道时遇到了麻烦。 scp可能正在等待您的密码吗?


第二个想法你的线路检测可能不起作用。这将导致跳跃超出您希望它退出的位置。也许你也应该检查'\r'


也有人做了类似的事情: How to read JSch command output?