首先,我在java上非常基础。我正在尝试浏览.txt文件并将其内容加载到文本区域。我完成了部分,直到我从JFileChooser收到文件,现在我不知道如何做其余的。
.
.
.
File selFile = new File(fileChooser.getSelectedfile());
/// From here I want to load its content to a textarea "txtArea"
答案 0 :(得分:11)
使用所有Swing文本组件支持的read(...)和write(...)方法。简单的例子:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
class TextAreaLoad
{
public static void main(String a[])
{
final JTextArea edit = new JTextArea(30, 60);
edit.setText("one\ntwo\nthree");
edit.append("\nfour\nfive");
JButton read = new JButton("Read TextAreaLoad.txt");
read.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileReader reader = new FileReader( "TextAreaLoad.txt" );
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );
br.close();
edit.requestFocus();
}
catch(Exception e2) { System.out.println(e2); }
}
});
JButton write = new JButton("Write TextAreaLoad.txt");
write.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter writer = new FileWriter( "TextAreaLoad.txt" );
BufferedWriter bw = new BufferedWriter( writer );
edit.write( bw );
bw.close();
edit.setText("");
edit.requestFocus();
}
catch(Exception e2) {}
}
});
JFrame frame = new JFrame("TextArea Load");
frame.getContentPane().add( new JScrollPane(edit), BorderLayout.NORTH );
frame.getContentPane().add(read, BorderLayout.WEST);
frame.getContentPane().add(write, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
答案 1 :(得分:1)
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(selFile));
String str;
while ((str = in.readLine()) != null) {
jtextArea.append(str);
}
} catch (IOException e) {
} finally {
try { in.close(); } catch (Exception ex) { }
}
答案 2 :(得分:0)
对于缩进和换行符,您必须在追加到文本区域之前使用“\ n”。
BufferedReader buff = null;
try {
buff = new BufferedReader(new FileReader(selFile));
String str;
while ((str = buff.readLine()) != null) {
jtextArea.append("\n"+str);
}
} catch (IOException e) {
} finally {
try { in.close(); } catch (Exception ex) { }
}
答案 3 :(得分:-1)
使用BufferedReader
逐行读取.text文件。然后,您可以将每一行附加到文本区域。