簡體   English   中英

如何使用 java 將文件內容保存為單個字符串

[英]how to save contents of a file as single string using java

我正在嘗試使用分隔符從文本文件中提取特定內容。 這是我的代碼:

File file = new File("C:\\Inputfiles\\message.txt"); 
BufferedReader br = new BufferedReader(new FileReader(file)); 
String st; 
while ((st=br.readLine()) != null) {
String[] strings = StringUtils.split(st, "------------");
System.out.println(strings);}

但結果,每一行都被分隔符分割並保存為數組。

任何人都可以建議我如何將文件中的內容保存為單個字符串,因此我只能將有限數量的行作為 Array.

您可以使用StringBuilderStringBuffer來做到這一點。

    File file = new File("C:\\Inputfiles\\message.txt");
    BufferedReader br = new BufferedReader(new FileReader(file));
    String st;
    while ((st=br.readLine()) != null) {
        String[] strings = StringUtils.split(st, "------------");
        StringBuilder singleString = new StringBuilder();

        for(String s : strings){
            singleString.append(s);
        }
        System.out.println(singleString.toString());
    }

謝謝大家,

我確實使用了以下更改

String contents = new String(Files.readAllBytes(Paths.get("C:\\Inputfiles\\message1.txt")));
                String[] splitted = StringUtils.split(contents, "-------");
                for(int i=0;i<splitted.length;i++)
                    System.out.println(splitted[i]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM