文件字节流
//从C盘拷贝图片到D盘
import java.io.*;
public class Test{
public static void main(String[] args)
{
FileInputStream fis=null;
FileOutputStream fos=null;
File f=new File("c:\\a.jpg");
try {
fis=new FileInputStream(f);
fos=new FileOutputStream("d:\\a.jpg");
byte buf[]=new byte[512];
while(fis.read(buf)!=-1){
fos.write(buf);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
fos.close();
fis.close();
}catch(Exception e2){
e2.printStackTrace();
}
}
}
}
文件字符流
/*
*文件字符流
*/
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test{
public static void main(String[] args)
{
FileReader fr=null;
FileWriter fw=null;
try{
fr=new FileReader("c:\\1.asm");
fw=new FileWriter("d:\\masm\\vvv.txt");
char c[]=new char[512];
while(fr.read(c)!=-1){
fw.write(c); //可能会造成末尾有乱码.可采用fw.write(c,0,n)
}
}catch(IOException e1){
e1.printStackTrace();
}finally{
try{
fw.close();
fr.close();
}catch(IOException e2){
e2.printStackTrace();
}
}
}
}
简易记事本
/*
*简易记事本开发
*/
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener{
public static void main(String[] args){
Test test=new Test();
}
JMenuBar jb=null;
JMenu jm=null;
JMenuItem jmi1=null;
JMenuItem jmi2=null;
JTextArea jta=null;
public Test()
{
jb=new JMenuBar();
this.setJMenuBar(jb);
jm=new JMenu("文件");
jb.add(jm);
jmi1=new JMenuItem("打开");
jmi1.addActionListener(this);
jm.add(jmi1);
jmi2=new JMenuItem("保存");
jmi2.addActionListener(this);
jm.add(jmi2);
jta=new JTextArea();
this.add(jta);
this.setSize(300,600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==jmi1)
{
JFileChooser jfc1=new JFileChooser();
jfc1.setDialogTitle("请选择文件...");
jfc1.showOpenDialog(null);
jfc1.setVisible(true);
String filename1=jfc1.getSelectedFile().getAbsolutePath();
FileReader fr=null;
BufferedReader br=null;
try{
fr=new FileReader(filename1);
br=new BufferedReader(fr);
String s="";
String allCon="";
while((s=br.readLine())!=null)
{
allCon+=s+"\r\n";
}
jta.setText(allCon);
}catch(Exception e1){
e1.printStackTrace();
}finally{
try{
br.close();
fr.close();
}catch(Exception e2){
e2.printStackTrace();
}
}
}else if(e.getSource()==jmi2){
JFileChooser jfc2=new JFileChooser();
jfc2.setDialogTitle("另存为...");
jfc2.showSaveDialog(null);
jfc2.setVisible(true);
String filename2=jfc2.getSelectedFile().getAbsolutePath();
FileWriter fw=null;
BufferedWriter bw=null;
try{
fw=new FileWriter(filename2);
bw=new BufferedWriter(fw);
bw.write(this.jta.getText());
}catch(Exception e3){
e3.printStackTrace();
}finally{
try{
bw.close();
fw.close();
}catch(Exception e4){
e4.printStackTrace();
}
}
}
}
}