![](/img/trans.png)
[英]Reading from one file using FileInputStream and writing to another file using FileOutputStream
[英]Will reading/writing an int value from/to a file using byte-oriented stream such as FileInputStream/FileOutputStream access the buffer/disk 4 times?
示例代码是:-
import java.io.*;
public class WriteInt{
public static void main(String [] args)
{
WriteInt obj = new WriteInt();
obj.write();
}
public void write(){
File file = null;
FileOutputStream out = null;
int [] arr = {6};
try{
file= new File("CheckSize.txt");
out = new FileOutputStream(file);
for(int i =0; i<arr.length;i++)
{
System.out.println("Trying to write to file:-"+ file);
out.write(arr[i]);
}
}
catch(IOException ioex){
ioex.printStackTrace();
}
finally{
if(out != null)
{
System.out.println("Closing the stream");
try{
out.close();
}
catch(IOException ioex){
ioex.printStackTrace();
}
}
else{
System.out.println("Stream not open");
}
}
}
}
由于我正在使用面向字节的流将数据写入文件; 我的问题是,数据将在每个步骤中以4个步骤(1个字节)写入文件。 考虑到int
为4个字节。 如果我错了,请纠正我。
out.write(arr [i])将只写入int的最低字节。 最好的解决方案是使用具有writeInt(int)方法的java.io.DataOutputStream。
DataOutputStream out = new DataOutputStream(new FileOutputStream("file"));
out.writeInt(arr[i]);
在您的示例中,您使用的是OutputStream.write(int),它仅写入提供的数字的字节表示形式-仅写入一个字节,请看一下OutputStream API 。 因此,您的文件将仅包含6个字节。如果尝试写入大于255的数字,则可能会出现异常。
基本上,OutputStream要求其子类仅实现write(int)方法,因此其他OutputStream方法将其字节发送到write(int)。 但是,FileOutputStream中的所有写方法都将被覆盖,并利用缓冲的本机调用,该调用可能尝试一次发送所有数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.