[英]Will reading/writing an int value from/to a file using byte-oriented stream such as FileInputStream/FileOutputStream access the buffer/disk 4 times?
Sample Code is :- 示例代码是:-
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");
}
}
}
}
Since I am using Byte-Oriented Stream to write data to a file; 由于我正在使用面向字节的流将数据写入文件; My Question is that will the data be written to file in 4 steps (1 byte) in each step.
我的问题是,数据将在每个步骤中以4个步骤(1个字节)写入文件。 Considering
int
to be of 4 bytes. 考虑到
int
为4个字节。 Please correct me if I am wrong. 如果我错了,请纠正我。
out.write(arr[i]) will write only the lowest byte of int. out.write(arr [i])将只写入int的最低字节。 The best solution is to use java.io.DataOutputStream which has writeInt(int) method.
最好的解决方案是使用具有writeInt(int)方法的java.io.DataOutputStream。
DataOutputStream out = new DataOutputStream(new FileOutputStream("file"));
out.writeInt(arr[i]);
In your example you are using OutputStream.write(int) which writes only byte representation of provided number - only one byte is writen, take a look to OutputStream API . 在您的示例中,您使用的是OutputStream.write(int),它仅写入提供的数字的字节表示形式-仅写入一个字节,请看一下OutputStream API 。 So your file will contain only one byte with 6. If you will try to write a number that is more than 255 - you can expect an exception.
因此,您的文件将仅包含6个字节。如果尝试写入大于255的数字,则可能会出现异常。
Basically OutputStream requires its subclasses to implement only write(int) method, so other OutputStream methods sends theirs bytes to write(int). 基本上,OutputStream要求其子类仅实现write(int)方法,因此其他OutputStream方法将其字节发送到write(int)。 However all write methods in FileOutputStream are overridden and utilizes buffered native call that probably tries to send all data at a time.
但是,FileOutputStream中的所有写方法都将被覆盖,并利用缓冲的本机调用,该调用可能尝试一次发送所有数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.