我有一个程序,我试图测试是否创建了一个文件(info.txt),如果是,在程序启动时将内容打开到JTextArea中。我该怎么做呢?我已经知道如何搜索并查看文件是否存在,只是无法在启动时将其打开到textArea
import javax.swing.*; // need it
import java.awt.*; //need it also
import java.awt.datatransfer.*;
import java.util.*;
import java.io.*;
import java.awt.event.*; //keeps track of events
import javax.swing.border.*; // not necessary / already imported ^^
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.util.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.border.*;
public class finalA extends JFrame implements ActionListener{
private final int WIDTH = 750;
private final int HEIGHT = 400;
static String theText;
private String text;
//creates components
private JTextArea textArea;
private JButton SaveB;
private JScrollPane scroll;
public finalA(){
setTitle("Super fancy text editor");
setSize(WIDTH,HEIGHT);
Container pane = getContentPane();
//Creates button
SaveB = new JButton("Save & Exit");
textArea = new JTextArea();
scroll = new JScrollPane(textArea);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//adds event handler for exit button
SaveB.addActionListener(this);
//sets pane to null
pane.setLayout(null);
//location of button and TA (750,400)
textArea.setLocation(10,100);
SaveB.setLocation(150,320);
//set size of TA and Button
textArea.setSize(730,200);
SaveB.setSize(100,30);
//add items to pane
pane.add(textArea);
pane.add(SaveB);
scroll.setBounds(10,100,730,200);
scroll.setVisible(true);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}//ends constructor
public void openFile()throws Exception{
File f = new File("info.txt");
if(f.exists()){
FileReader reader = null;
try{
reader = new FileReader("info.txt");
textArea.read(reader, null);
}
finally{
if (reader != null){
reader.close();
}
}
}
}//ends openFile
public void actionPerformed(ActionEvent e){
String text = textArea.getText();
if(e.getActionCommand().equals("Save & Exit")){
try{
BufferedWriter reader = new BufferedWriter(new FileWriter(new File("info.txt"),true));
reader.write(text);
reader.newLine();
reader.close();
}catch(IOException E){
System.out.println("the error is " + E);
}
}
System.exit(0);
}
}// ends finalA class
因此,根据可用的代码,在创建了JTextArea
openFile
public TestRead() {
//...
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
openFile();
} catch (IOException exp) {
exp.printStackTrace();
}
}//ends constructor
不要使用null
布局,像素完美的布局在现代GUI设计中是一种错觉。你无法控制字体指标、DPI或渲染管道等因素,这些因素都可能改变组件的个人需求。
Swing被设计为使用布局管理器,并且许多更新界面的功能都与之相关。如果你不使用布局管理器,你要做好没完没了的工作和挫折的准备
使用文件读取器流(如Scanner)加载文件,然后在文本区添加文本。
下面是一个简单的示例:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
/*
* simple demo to load file to textarea
*/
public class FileLoaderTest {
public static void main(String[] args) throws IOException{
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
JFrame frame = new JFrame("Load File Demo");
JPanel panel = new JPanel();
JButton btnLoad = new JButton("Load File");
final JTextArea textArea = new JTextArea(10,20);
btnLoad.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
fileChooser.setFileFilter(new FileNameExtensionFilter
("Text File", "txt"));
fileChooser.setAcceptAllFileFilterUsed(false);
while(true)
{
if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ) {
if(!fileChooser.getSelectedFile().exists()) {
JOptionPane.showMessageDialog(fileChooser,
"You must select an existing file!","open File",
JOptionPane.ERROR_MESSAGE);//continue
}else {
//read file to the textArea
File file = fileChooser.getSelectedFile();
try {
Scanner scanner = new Scanner(new BufferedReader
(new FileReader( file)));
while(scanner.hasNext()) {
textArea.append(scanner.nextLine()+"n");
}
scanner.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;//successfully open break
}
}else {
break;//user cancel open break
}
}
}
});
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(btnLoad);
frame.add(panel,BorderLayout.NORTH);
frame.add(scrollPane,BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
从你的问题来看,我想你已经明白了:
BufferedReader in = null;
try{
in = new BufferedReader(new FileReader("C:\path\to\file\info.txt"));
String str = in.readLine();
ArrayList<String> textList = new ArrayList<String>();
while((str = in.readLine()) != null){
textList.add(str); //saves each line that is read from the file
}
//-->This is where you will add later code
}catch(IOException e){
System.out.println("Error reading file");
e.printStackTrace();
}
从这里你应该使用JTextArea.append()
方法,像这样:
——在readFile()方法的while循环之后插入
for(String s:textList){
yourJTextArea.append(s +"n");
}
完整示例:
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class TextRead extends JFrame{
static JTextArea mytextArea;
public TextRead(){
super("TextRead");
mytextArea = new JTextArea();
mytextArea.setPreferredSize(new Dimension(500,500));
getContentPane().add(mytextArea);
setContentPane(getContentPane());
pack();
setVisible(true);
setSize(500,500);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
readFile();
}
private void readFile() {
BufferedReader in = null;
try{
String path = "C:\Users\steve_000\Desktop\info.txt"; //<--your path goes here!
in = new BufferedReader(new FileReader(path));
String str = in.readLine();
ArrayList<String> textList = new ArrayList<String>();
while((str = in.readLine()) != null){
textList.add(str); //saves each line that is read from the file
}
for(String s: textList){
mytextArea.append(s + "n"); //prints each line consecutively
}
}catch(IOException e){
System.out.println("Error reading file");
e.printStackTrace();
}
}
public static void main(String... args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
runGUI();
}
});
}
public static void runGUI() {
TextRead tr = new TextRead();
JFrame.setDefaultLookAndFeelDecorated(false);
}
}