Java NIO。模拟基本下载应用程序的有效解决方案是不是?
我试图通过复制myBook.txt
这样的文件并将其保存为同一Java包中的newBook.txt
来模拟一个简单的下载应用程序
我已经设法让它在我的工作站上工作,但我该如何让它在另一台工作站上工作呢?我提供的路径在项目名称之前是不同的,例如"SimpleDownloadCentre\\..."
private final String SOURCE_PATH = "C:\\Users\\...\\Documents\\NetBeansProjects\\"
+ "SimepleDownloadCentre\\src\\simpledownloadcentre\\"
+ "myBook.txt";
private final String DESTINATION_PATH = "C:\\Users\\...\\Documents\\NetBeansProjects\\"
+ "SimepleDownloadCentre\\src\\simpledownloadcentre\\"
+ "newBook.txt";
public void startDownload() {
FileInputStream fis = null;
try {
String destination = DESTINATION_PATH;
String source = SOURCE_PATH;
fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination);
FileChannel fci = fis.getChannel();
FileChannel fco = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
try {
int read = fci.read(buffer);
if (read == -1) {
break;
}
buffer.flip();
fco.write(buffer);
buffer.clear();
} catch (IOException ex) {
System.err.println("ERROR: unable to read block");
}
}
} catch (FileNotFoundException ex) {
System.err.println("ERROR: file not found");
} finally {
try {
fis.close();
} catch (IOException ex) {
System.err.println("ERROR: unable to close file channel");
}
}
}
Java NIO是我想要的解决方案的错误方法吗
提前谢谢
# 1 楼答案
NIO不是一个问题,尽管它不会比使用IO更有帮助
我要做的是:
当然,您可以使用普通IO完成所有这一切(直接缓冲区除外)
如果您不需要套接字,只想传输数据,我会使用transferTo/transferFrom来执行复制
总之:使用NIO不是一个坏主意,也不是一个好主意
# 2 楼答案
你的复制循环不正确。如果write()不写入整个缓冲区,它可能会丢失数据。内容如下: