?? file_rw.java
字號:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class File_RW extends JFrame implements ActionListener{
String str_area,str_text;
char ch_text;
JLabel label1=new JLabel("文本文件的讀寫");
//label1.setFont(new Font("Serif",Font.PLAIN,20));
JLabel label2=new JLabel("請輸入文件名:");
JTextArea t1=new JTextArea(6,20);
JTextField t2=new JTextField(12);
JButton read=new JButton("讀取");
JButton write=new JButton("寫入");
JButton exit=new JButton("退出");
public File_RW(){
setTitle("文件讀寫");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JPanel p4=new JPanel();
JPanel p5=new JPanel();
JPanel p6=new JPanel();
JPanel p7=new JPanel();
JPanel p8=new JPanel();
JPanel p9=new JPanel();
JPanel p10=new JPanel();
JScrollPane scroll=new JScrollPane(t1);
p1.setLayout(new FlowLayout());
p1.add(label1);
p2.setLayout(new FlowLayout());
p2.add(scroll);
p3.setLayout(new BorderLayout());
p3.add("North",p1);
p3.add("South",p2);
p4.setLayout(new BorderLayout());
p4.add("North",label2);
p5.setLayout(new FlowLayout());
p5.add(t2);
p6.setLayout(new BorderLayout());
p6.add("North",p4);
p7.setLayout(new FlowLayout());
p7.add(read);
p7.add(write);
p7.add(exit);
p8.setLayout(new BorderLayout());
p8.add("North",p3);
p8.add("Center",p6);
p8.add("South",p7);
add(p8);
read.addActionListener(this);
write.addActionListener(this);
exit.addActionListener(this);
setBounds(250,200,300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==read){
try{read();}
catch(IOException ioe) {}
}
if(e.getSource()==write){
try{write();}
catch(IOException ioe) {}
}
if(e.getSource()==exit)
System.exit(0);
}
public void read() throws IOException{
str_text=t2.getText();
File f=new File(str_text);
if(!f.exists()){JOptionPane.showMessageDialog(File_RW.this,"文件"+str_text+"不存在!!");}
FileReader in=new FileReader(str_text);
BufferedReader bin=new BufferedReader(in);
String str;
while((str=bin.readLine())!=null){
t1.append(str+"\r\n");
}
in.close();
JOptionPane.showMessageDialog(File_RW.this,"文件讀取成功!!");
}
public void write()throws IOException{
str_text=t2.getText();
FileOutputStream fout=new FileOutputStream(str_text,true);
DataOutputStream dout=new DataOutputStream(fout);
String str,str_1;
str=t1.getText();
str_1=turn(str);
int m=str_1.length();
t1.append("\r\n寫入了"+String.valueOf(m)+"字符\n");
dout.writeBytes(str_1);
dout.close();
JOptionPane.showMessageDialog(File_RW.this,"文件已成功寫入"+str_text+"中!!");
}
public String turn(String str){
while(str.indexOf("\n")!=-1){
str=str.substring(0,str.indexOf("\n"))+"<br>"+str.substring(str.indexOf("\n")+1);
}
while(str.indexOf(" ")!=-1){
str=str.substring(0,str.indexOf(" "))+" "+str.substring(str.indexOf(" ")+1);
}
return str;
}
public static void main(String arg[]){
File_RW t=new File_RW();
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -