gpt4 book ai didi

java - 如何打开网络上的 txt 文件并将其内容读取为字符串?

转载 作者:行者123 更新时间:2023-11-30 03:58:17 28 4
gpt4 key购买 nike

我四处寻找如何做到这一点,并且不断寻找不同的解决方案,但没有一个对我来说效果很好,我不明白为什么。 FileReader 只适用于本地文件吗?我尝试了在网站上找到的脚本组合,但它仍然不太有效,它只是抛出一个异常,并给我留下了变量内容的错误。这是我一直未成功使用的代码:

public String downloadfile(String link){
String content = "";
try {
URL url = new URL(link);
URLConnection conexion = url.openConnection();
conexion.connect();
InputStream is = url.openStream();
BufferedReader br = new BufferedReader( new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
content = sb.toString();
br.close();
is.close();
} catch (Exception e) {
content = "ERROR";
Log.e("ERROR DOWNLOADING",
"File not Found" + e.getMessage());
}
return content;
}

最佳答案

使用它作为下载器(提供保存文件的路径(以及扩展名)和文本文件的确切链接)

    public static void downloader(String fileName, String url) throws IOException {
File file = new File(fileName);

url = url.replace(" ", "%20");
URL website = new URL(url);
if (file.exists()) {
file.delete();
}
if (!file.exists()) {
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(fileName);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();

}
}

然后调用该函数读取文本文件

   public static String[] read(String fileName) {
String result[] = null;
Vector v = new Vector(10, 2);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String tmp = "";
while ((tmp = br.readLine()) != null) {
v.add(tmp);
}
Iterator i = v.iterator();
result = new String[v.toArray().length];
int count = 0;
while (i.hasNext()) {
result[count++] = i.next().toString();
}

} catch (IOException ioe) {
ioe.printStackTrace();
}


return (result);
}

最后是main方法

        public static void main(){
downloader("D:\\file.txt","http://www.abcd.com/textFile.txt");
String data[]=read("D:\\file.txt");
}

关于java - 如何打开网络上的 txt 文件并将其内容读取为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22554866/

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