我的服务器中有一个文本文件。我正在从客户端下载该文件。我已经给出了应保存它的文件路径fi
。
创建的文本文件,其中有一些丑陋的字符,而不是字符串。我该如何纠正它?
输出的格式为;
sNULdNULiNULdNUL
打印文本文件中的一个字符,后跟粗体的NUL。这是什么?我怎样才能摆脱它?
FileOutputStream f= new FileOutputStream(fi);
DataOutputStream d= new DataOutputStream(f);
String fc;
while((fc = re.readLine()) !=null)
{
System.out.println(fc);
d.writeChars(fc);
d.flush();
}
更新
€À€À€À€À€À€À€À€À€À€À€À€À€À€À€
更新2
InputStreamReader st= new InputStreamReader(
s.getInputStream());
re= new BufferedReader(st);
和s
是这里的socket
。 re
已初始化为 BufferedReader re;
try {
s= new Socket("localhost", "2222");
} catch (IOException ex) {
ex.printStackTrace();
}
最佳答案
当您希望将字符串存储在内存中、将其写入文件或通过互联网发送时,需要将字符串编码为字节。有许多编码系统可以执行此操作。
writeChars
将每个字符写入两个字节,这就是您已经看到的。
writeUTF
做了一些人类不可读的事情:
Writes a string to the underlying output stream using Java modified UTF-8 encoding in a machine-independent manner.
First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of str, and at most two plus thrice the length of str.
如果您希望轻松地将字符写入文件,请使用 FileWriter 。在大多数情况下,它会假设编写人类可读文件的正确默认值。
FileWriter fw = new FileWriter(filename);
BufferedWriter bw = new BufferedWriter(fw);
while((fc = re.readLine()) !=null) {
bw.write(fc);
bw.newLine();
bw.flush();
}
bw.close();
关于java - 将字节数组保存到文件时显示丑陋的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14535737/