Hello! I am familiar with Java recently, trying to create simple window applications, stuck on the topic of opening a file through filechooser. In particular, you need to open a text document and display its contents in text processing components, such as textPane. My code opens the file, but does not display all the contents in the textPane, but only the last line. Apparently having read one line, it does not go to a new line in the component and reads a new line from the file to the same line, although everything should work according to the code. I can not understand how to fix it, tell me?

JButton btnNewButton_1 = new JButton("Открыть"); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory(new java.io.File("C:/")); fc.setDialogTitle("Блокнотец"); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { /// try { FileReader fr = new FileReader(fc.getSelectedFile()); BufferedReader br = new BufferedReader(fr); String str; while ((str = br.readLine()) != null) { System.out.println(str + "\n"); textPane.setText(str + "\n"); } br.close(); } catch (IOException e0) { System.out.println("Файл не найден!"); } /// } } }); 

    1 answer 1

     try { FileReader fr = new FileReader(fc.getSelectedFile()); BufferedReader br = new BufferedReader(fr); String text=""; String str; while ((str = br.readLine()) != null) { System.out.println(str + "\n"); text+=str; } textPane.setText(text); br.close(); } catch (IOException e0) { System.out.println("Файл не найден!"); } 

    or so

     try { FileReader fr = new FileReader(fc.getSelectedFile()); BufferedReader br = new BufferedReader(fr); StringBuilder text= new StringBuilder(); String str; while ((str = br.readLine()) != null) { System.out.println(str + "\n"); text.append(str); text.append('\n'); } textPane.setText(text.toString()); br.close(); } catch (IOException e0) { System.out.println("Файл не найден!"); } 

    He does not have to go anywhere. setText () changes all text to the one passed in the parameter.

    • Indeed, I tried the first method - everything works fine! Thank you very much! I just had to add "\ n" to str in order to switch to a new line, but it turns out to be a continuous line .... otherwise what’s needed. Tell me, which of these methods is more suitable for working with large files? - Tim Leyden
    • one
      Yes, I really missed the line break). It is better to use StringBuiler, because text + = str will constantly create a new String object that will affect memory - Ziens