【问题标题】:NewLines missing while writing to ByteArrayOutputStream写入 ByteArrayOutputStream 时缺少新行
【发布时间】:2017-07-26 00:13:04
【问题描述】:

我正在尝试读取 txt 文件并使用套接字从中传递数据,但看起来我在写入输出流时缺少换行符。

我的txt文件是:

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  }
}

字节数组输出流:

{ "firstName": "John", "lastName": "Smith", "isAlive": 真,“年龄”:25,“地址”:{%“街道地址”:“21 2nd 街道”,“城市”:“纽约”,“州”:“纽约”,
"邮政编码": "10021-3100" }}


扫描仪:

private byte[] readFile(String path) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);

    File file = new File(path);
    Scanner scanner = new Scanner(file);

    while (scanner.hasNextLine()){
        out.writeUTF(scanner.nextLine());
    }

    byte[] bytes = baos.toByteArray();
    return bytes;
}

编辑:

System.getProperty("line.separator"); 

帮我换行了,但我在baos 中仍然得到一些无效字符

System.out.println(new String(baos.toByteArray()));

【问题讨论】:

标签: java


【解决方案1】:

用下面的代码重写

while (scanner.hasNextLine()){
        out.writeUTF(scanner.nextLine()+"\n");
    }

【讨论】:

  • 换行符不是在每个系统上都 \n 所以最好使用 System.getProperty("line.separator")
【解决方案2】:

看来.flush() 帮我清除了无效字符...

private byte[] readFile(String path) throws IOException {

    DataOutputStream out = new DataOutputStream(socket.getOutputStream());

    File file = new File(path);
    Scanner scanner = new Scanner(file);

    while (scanner.hasNextLine()){
        out.writeUTF(scanner.nextLine() + System.getProperty("line.separator"));
    }

    byte[] bytes = out.toByteArray();
    out.flush();
    return bytes;
}

What is the purpose of flush() in Java streams?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2019-07-06
    • 1970-01-01
    相关资源
    最近更新 更多