[英]DataOutputStream not generating bytes as output?
DataOutputStream
Class is used to write the primitive data types as binary format. DataOutputStream
类用于将原始数据类型编写为二进制格式。 I have been using the methods void writeChars(String s)
of DataOutputStream
class,to write it in a file using the program... 我一直在使用
DataOutputStream
类的void writeChars(String s)
方法,以使用程序将其写入文件中...
public class FileDemo {
public static void main(String[] args) throws IOException{
String x= "haha";
DataOutputStream out = new DataOutputStream(new FileOutputStream("E:/a.txt"));
out.writeChars(x);
out.close();
}
}
The file a.txt now has the following text as output(all chars separated by space): 现在,文件a.txt具有以下文本作为输出(所有字符用空格分隔):
h a h a
My question is why does the file not having the string as bytes?? 我的问题是为什么文件没有字符串作为字节? And please also explain that why there is a need to use PrintWriter when we can use functions of DataOutputStream to write all primitives...
并且还请说明为什么我们可以使用DataOutputStream函数编写所有原语时为什么需要使用PrintWriter ...
The DataOutputStream
does exactly what it is for. DataOutputStream
完全可以实现其目的。 It writes the chars as bytes. 它把字符写为字节。 One char is made up of two bytes.
一个字符由两个字节组成。
So it writes the chars haha
as bytes 所以它把字符
haha
写成字节
0, 104, 0, 97, 0, 104, 0 ,97
because char h
is represented as the two bytes 0, 104
. 因为char
h
表示为两个字节0, 104
。
When you open the file in your text editor it tries to interprete the bytes according to a specified encoding. 当您在文本编辑器中打开文件时,它将尝试根据指定的编码来解释字节。 Notepad for example will use ANSI by default.
例如,记事本默认情况下将使用ANSI。
If you open the file in Notepadd++ it can shows you the 0
bytes. 如果在Notepadd ++中打开文件,它将显示
0
字节。
Use an OutputStreamWriter if you want the char to be converted to the byte representation of a defined encoding. 如果要将字符转换为已定义编码的字节表示,请使用OutputStreamWriter 。 Eg
例如
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(
"C:/Dev/a.txt"), Charset.forName("windows-1252"));
out.write(x);
out.close();
This will output the bytes 这将输出字节
104, 97, 104, 97
Are you looking for writeBytes(s) ? 您是否在寻找writeBytes(s)? Or are you wondering why the file doesn't contain something like 1010101010 ?
还是您想知道为什么文件不包含1010101010之类的内容?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.