java对文件的读取和保存操作,java读取保存,import java.
分享于 点击 47350 次 点评:234
java对文件的读取和保存操作,java读取保存,import java.
import java.awt.FlowLayout;import java.awt.TextArea;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.text.SimpleDateFormat;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;public class ReadAndWriteText extends JFrame implements ActionListener{ TextArea text=new TextArea(15,30); JButton Read=new JButton("读取文件"); JButton Save=new JButton("保存文件"); JPanel btnpnl=new JPanel(); File file=new File("text.txt"); ReadAndWriteText(){ btnpnl.setLayout(new FlowLayout(FlowLayout.CENTER,20,20)); btnpnl.add(Read); btnpnl.add(Save); Read.addActionListener(this); Save.addActionListener(this); this.setLayout(new FlowLayout()); this.add(btnpnl); this.add(text); this.setBounds(450, 150, 300, 400); this.setVisible(true); this.validate(); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } private void save() { System.out.println(file.getAbsolutePath());//获得绝对路径 try { FileWriter fw=new FileWriter(file); BufferedWriter bfw=new BufferedWriter(fw); String str=new String(); str=text.getText(); bfw.write(str, 0, str.length()); bfw.flush(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } private void read() { // TODO Auto-generated method stub try { FileReader fr=new FileReader(file); BufferedReader bfr=new BufferedReader(fr); String str=new String(); while((str=bfr.readLine())!=null){ text.append(str+"\n"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(Save==e.getSource()){ save(); System.out.print("writing"); } if(Read==e.getSource()){ read(); System.out.print("reading"); } } public static void main(String []args){ new ReadAndWriteText(); // System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ssss")).format(time2)); }}
用户点评