从一个.txt中读取其内容,文本中有类似信息如下:信息1信息2信息3。。。我写的代码是:publicclassFileMessage{publicstaticvoidmain(String[]args)throwsException{Filefile=newFile("D:"+File.separator+"test.txt");if(!file.exists()){thrownewException("抱歉,您请求的文件路径不存在!");}InputStreamis=newFileInputStream(file);byte[]byt=newbyte[(int)file.length()];is.read(byt);is.close();Stringresult=newString(byt);result.replace("\r","");result.replace("\n","");System.out.println("从文件中读到的结果:"+result);}}读到的数据总是分成了多行,但需求需要显示在一行,想请教一下大家为什么replace()方法没有起作用,去掉字符串里面的换行符呢?或者有没有其他更优雅一些的实现方法呢?
2 回答
慕妹3146593
TA贡献1820条经验 获得超9个赞
java.nio.file.Files这个工具类有提供流式操作文本文件的API,对于你的需求:Files.lines(Paths.get("D:","test.txt")).collect(Collectors.joining());
慕无忌1623718
TA贡献1744条经验 获得超4个赞
java8写法:returnnewBufferedReader(newFileReader(file)).lines().collect(Collectors.joining());
添加回答
举报
0/150
提交
取消
