首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Java中为字节数组添加换行符?

问如何在Java中为字节数组添加换行符?
EN

Stack Overflow用户
提问于 2016-09-09 19:34:46
回答 2查看 17K关注 0票数 1

下面这段代码尝试在字节数组中引入换行符,并将字节数组写入文件。

代码语言:javascript
复制
import java.io.*;
public class WriteBytes {
    public static void main(String args[]) {
        byte[] cities = { 'n', 'e', 'w', 'y', 'o', 'r', 'k', '\n', 'd', 'c' };
        FileOutputStream outfile = null;
        try {
            outfile = new FileOutputStream("newfile.txt");
            outfile.write(cities);
            outfile.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

新文件的内容是:newyorkdc

我所期望的是:

纽约

数据中心

我试图将'\n'类型转换为(byte)'\n',但无济于事。

解决方案:将数组初始化更改为

代码语言:javascript
复制
byte[] cities = { 'n', 'e', 'w', 'y', 'o', 'r', 'k', '\r','\n', 'd', 'c' };

我使用了Notepad++来查看文件的内容,我认为它取消了换行符,但接受了回车和换行符组合。

EN

回答 2

Stack Overflow用户

发布于 2016-09-09 19:46:51

换行符依赖于操作系统,您应该调用System.getProperty("line.separator")来检索它

或者更好的做法是,如果您正在编写文本文件,则应该使用具有newLine()方法的BufferedWriter来编写独立于操作系统的行分隔符

票数 4
EN

Stack Overflow用户

发布于 2016-09-09 19:48:59

您可以通过读取和打印文件来证明它是有效的。

代码语言:javascript
复制
import java.io.*;


public class Main {
    public static void main(String args[]) {
        String filename = "newfile.txt";
        byte[] cities = {'n', 'e', 'w', 'y', 'o', 'r', 'k', '\n', 'd', 'c'};
        FileOutputStream outfile = null;
        try {
            outfile = new FileOutputStream(filename);
            outfile.write(cities);
            outfile.close();

            BufferedReader in = new BufferedReader(new FileReader(filename));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        byte[] cities2 = {'n', 'e', 'w', 'y', 'o', 'r', 'k', 'd', 'c'};
        outfile = null;
        try {
            outfile = new FileOutputStream(filename);
            outfile.write(cities2);
            outfile.close();

            BufferedReader in = new BufferedReader(new FileReader(filename));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

测试

代码语言:javascript
复制
newyork
dc
newyorkdc
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39410670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档