在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  HTML/ Java 讀文件內(nèi)容如何顯示在一行上

Java 讀文件內(nèi)容如何顯示在一行上

從一個.txt中讀取其內(nèi)容,文本中有類似信息如下:
信息1
信息2
信息3
。。。
我寫的代碼是:
public class FileMessage {

public static void main(String[] args) throws Exception {
    File file  = new File("D:"+File.separator+"test.txt");
    if(!file.exists()){
        throw new Exception("抱歉,您請求的文件路徑不存在!");
    }
    InputStream is = new FileInputStream(file);
    byte[] byt = new byte[(int)file.length()]; 
    is.read(byt);
    is.close();
    String result = new String(byt);
    result.replace("\r", "");
    result.replace("\n", "");
    System.out.println("從文件中讀到的結(jié)果:"+result);
}

}
讀到的數(shù)據(jù)總是分成了多行,但需求需要顯示在一行,想請教一下大家為什么replace()方法沒有起作用,去掉字符串里面的換行符呢?或者有沒有其他更優(yōu)雅一些的實(shí)現(xiàn)方法呢?

回答
編輯回答
獨(dú)特范

java.nio.file.Files 這個工具類有提供流式操作文本文件的 API,對于你的需求:

Files.lines(Paths.get("D:", "test.txt")).collect(Collectors.joining());
2018年8月5日 19:58
編輯回答
使勁操

java8寫法:

return new BufferedReader(new FileReader(file)).lines().collect(Collectors.joining());
2018年6月26日 15:36
編輯回答
糖果果

public class FileMessage2 {

public static void main(String[] args) throws Exception {
    File file  = new File("D:"+File.separator+"test.txt");
    if(!file.exists()){
        throw new Exception("抱歉,您請求的文件路徑不存在!");
    }

// InputStream is = new FileInputStream(file);
// byte[] byt = new byte[(int)file.length()];
// is.read(byt);
// is.close();
// String result = new String(byt);
// result.replace("rn", "");

    
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    StringBuffer sb = new StringBuffer();
    String str;
    while((str=br.readLine())!=null){
        sb.append(str);
    }
    br.close();
    fr.close();
    System.out.println("從文件中讀到的結(jié)果:"+sb);
}

}
采用了一種按行讀取的方式解決了,但是我還是不知道一開始的寫法里replace()方法為何無效,悲:-(

2018年3月2日 14:39
編輯回答
薔薇花

怎么做上面說清了。我來回答一下為什么不變~
String對象是不可變的,所以你這里的result是改變不了的。replace()方法是生成了一個新的String對象,所以如果你要改的話,可以這么做:

String result = "aaaaa";
result = result.replace("a", "b");
2018年2月25日 17:38
編輯回答
荒城

第一: 可以用一行一行的讀,然后拼接起來。
第二: result.replace("rn","");

2018年5月28日 17:38