java 如何使用java读取存储在服务器上的文件内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28693171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read content of file stored on server using java?
提问by Cristian Sevescu
How to read file stored on server using java? I have .txt file stored on server, how to read contents of it.
如何使用java读取存储在服务器上的文件?我在服务器上存储了 .txt 文件,如何读取它的内容。
String test, newq;
newq = "http://www.example.com/pqr.txt";
test = new String(Files.readAllBytes(Paths.get(newq)));
// variable test should contain pqr.txt content
What I am doing wrong?
我做错了什么?
回答by Cristian Sevescu
That code works fine for files found in the file system. Path object is designed specifically for this.
该代码适用于在文件系统中找到的文件。Path 对象是专门为此设计的。
When you want to access a remote file, it no longer works.
当您想访问远程文件时,它不再起作用。
One easy way to read the file is this:
读取文件的一种简单方法是:
URL url = new URL("https://wordpress.org/plugins/about/readme.txt");
String text = new Scanner( url.openStream() ).useDelimiter("\A").next();
It is not very pretty but it is small, it works and does not require any library.
它不是很漂亮,但很小,它可以工作并且不需要任何库。
With Apache Commons you can do it like this:
使用 Apache Commons,您可以这样做:
URL url = new URL("https://wordpress.org/plugins/about/readme.txt");
String text = IOUtils.toString(url.openStream());
回答by fge
Go through an HttpURLConnection
and use a StringBuilder
. Sketch code:
通过 anHttpURLConnection
并使用 a StringBuilder
。草图代码:
final URL url = new URL("http://www.example.com/pqr.txt");
final StringBuilder sb = new StringBuilder();
final char[] buf = new char[4096];
final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT);
try (
final InputStream in = url.openStream();
final InputStreamReader reader = new InputStreamReader(in, decoder);
) {
int nrChars;
while ((nrChars = reader.read(buf)) != -1)
sb.append(buf, 0, nrChars);
}
final String test = sb.toString();