gpt4 book ai didi

java - java I/O字节流类的查询

转载 作者:行者123 更新时间:2023-12-01 18:21:37 24 4
gpt4 key购买 nike

下面是创建单独的字节流以读取和写入同一文件的程序。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyNoBuffer{
public static void main(String[] args){
FileInputStream in = null;
FileOutputStream out = null;
Long startTime, elapsedTime;

//String inFileStr = "C:\\project\\books\\java-Preparation\\main_docs\\practice.jpg";
//String outFileStr = "C:\\project\\books\\java-Preparation\\main_docs\\practice_out.jpg";
String fileStr = "C:\\project\\books\\java-Preparation\\main_docs\\practice.jpg";

File file = new File(fileStr);
System.out.println("File size before - r/w is: " + file.length() + " bytes");
try{
in = new FileInputStream(fileStr);
out = new FileOutputStream(fileStr);

startTime = System.nanoTime();
int byteRead;

while((byteRead = in.read()) != -1){
out.write(byteRead);
}

elapsedTime = System.nanoTime() - startTime;
System.out.println("Elapsed Time is: " + (elapsedTime/1000000.0) + " msec");
System.out.println("File size after - r/w is: " + file.length() + " bytes");

}catch(IOException ex){
ex.printStackTrace();
}finally{
try{
if(in != null){
in.close();
}
if(out != null){
out.close();
}
}catch(IOException ex){
ex.printStackTrace();
}
}


}
}

以下是观察结果:

File size before - r/w is: 1115512 bytes
Elapsed Time is: 0.040711 msec
File size after - r/w is: 0 bytes

我知道FileInputStreamFileOutputStream是非缓冲字节流I/O类。

我希望写入同一文件后文件大小保持不变。

文件大小变为零的潜在原因是什么?

注意:正在学习 java 1.6 I/O

最佳答案

[...]for reading from and writing into same file.

永远不要这样做。曾经

结果是不可预测的。

如果您想修改文件的内容,请将新内容写入文件中,然后自动重命名为旧文件 - 之后您已确保新内容写入成功。

此外,现在是 2014 年,所以除非您真的必须使用 Java 6,use java.nio.file instead ,特别是如果您必须重命名,因为 File will leave you stranded more often than not .

带有 java.nio.file 的示例代码:

final Path toChange = Paths.get("pathtoyourfilehere");
final Path dir = toChange.getParent();
final Path tmpfile = Files.createTempFile(dir, "foo", "bar");

try (
final InputStream in = Files.newInputStream(toChange);
final InputStream out = Files.newOutputStream(tmpfile);
) {
// Work with in and out
}

// Then move!
try {
Files.move(tmpfile, toChange, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException ignored) {
Files.move(tmpfile, toChange, StandardCopyOption.REPLACE_EXISTING);
}

关于java - java I/O字节流类的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27589495/

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