【发布时间】:2021-06-29 15:49:22
【问题描述】:
我正在尝试使用 Java 从 REST API 下载几个不同的文件。
到目前为止,我正在获取文件,但内容不会附加到输出文件的末尾。
我将FileOutputStream 构造函数从new FileOutputStream(path) 更改为new FileOutputStream(path, true),但不知何故它不起作用。
有人可以提供我所缺少的指针吗?
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class GetXML {
// This Method Is Used To Download A Sample File From The Url
private static void downloadFileFromUrlUsingNio() {
String filePath ="config/sample.txt";
Scanner in = new Scanner(System.in);
System.out.println("Enter the NO which you want to parse: ");
while(in.hasNextLine()){
String sampleUrl = "e.g.comSearch?NO=" + in.nextLine();
URL urlObj = null;
ReadableByteChannel rbcObj = null;
FileOutputStream fOutStream = null;
// Checking If The File Exists At The Specified Location Or Not
Path filePathObj = Paths.get(filePath);
boolean fileExists = Files.exists(filePathObj);
if(fileExists) {
try {
urlObj = new URL(sampleUrl);
rbcObj = Channels.newChannel(urlObj.openStream());
fOutStream = new FileOutputStream(filePath, true);
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
System.out.println("! File Successfully Downloaded From The Url !");
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());
} finally {
try {
if(fOutStream != null){
fOutStream.close();
System.out.println("fOutStream closed");
}
if(rbcObj != null) {
rbcObj.close();
System.out.println("rbcObj closed");
}
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
}
}
} else {
System.out.println("File Not Present! Please Check!");
}
}
in.close();
System.out.println("Scanner Closed");
}
public static void main(String[] args) {
downloadFileFromUrlUsingNio();
}
}
【问题讨论】:
-
运行时会打印什么?
-
@OneCricketeer "!文件从 URL 成功下载!",fOutStream 关闭,rbcObj 关闭,当我有 1 个输入字符串时扫描仪关闭
-
1) 你没有关闭从
fOutStream获取的频道。 --- 2) 你应该检查transferFrom(...)的返回值。 --- 3) 你应该使用 try-with-resources.