有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java每次向字符串添加一行

我有一个程序,可以让你打开一个文件,然后用下面的代码一次把它读入一个JTextArea

 try{
    String fileContents = new Scanner(new File(fileName)).useDelimiter("\\Z").next();
  }catch(FileNotFoundException ex){
    ex.printStackTrace();
  }

  myTextArea.setText(fileContents);

这是有效的。但我的问题是,如何将其读入我的fileContents字符串中,并在每次获得新行字符时仍将其添加到换行符中

这是我所拥有的,但这将它全部放在我的文本区域的一行中:

 try{
Scanner contentsTextFile = new Scanner(new File(fileName));
while(contentsTextFile.hasNext()){
    fileContents = contentsTextFile.useDelimiter("\r\n|\n").nextLine(); 
    }

}catch(FileNotFoundException ex){
    ex.printStackTrace();
}

   myTextArea.setText(fileContents);

我想看到的是,这行文本使用分隔符获得一个新行,该分隔符一次只读取一行,而不是整个文件

有人能帮忙吗


共 (2) 个答案

  1. # 1 楼答案

    最简单的方法是使用^{},其中:

    Initializes from a stream. This creates a model of the type appropriate for the component and initializes the model from the stream. By default this will load the model as plain text. Previous contents of the model are discarded.

  2. # 2 楼答案

    您可以使用BufferedReader逐行读取文件,并对每一行读取使用JTextAreaappend()方法。为方便起见,将JTextArea包装成大小合适的JScrollPane,如图here。如果您预期任何延迟,请使用^{}在后台读取,并在process()中调用append()

    BufferedReader in = new BufferedReader(new FileReader(fileName));
    String s;
    while ((s = in.readLine()) != null) {
        myTextArea.append(s + "\n");
    }