java - 将字节数组保存到文件时显示丑陋的字符

标签 java bufferedreader dataoutputstream

我的服务器中有一个文本文件。我正在从客户端下载该文件。我已经给出了应保存它的文件路径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是这里的socketre 已初始化为 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/

相关文章:

java - 在 Java 中传回两个变量的最用户友好的方式?

java/opengl : loading textures on 64bit VM

java - Servlet 到达 BufferedReader 会超时?

java - 使用 FSDataOutputStream 从 Java REST-API 写入 HadoopDFS 的不需要的字符

java - 如何将整数的 "word"表示形式写入 Java 中的文件?

java - 如何使 DataOutputStream 将 boolean 值或整数写入 txt 文件?

java - 如何编写字符串扁平化器?

java - MappingException hibernate 映射列

java - 使用 BufferedReader 读取多个文件(使用 String[] args)

java - 从 BufferedReader 中的类型中查找 arrayList 中最大和最小的元素