java学习

来源:互联网 发布:软件到期时间破解 编辑:程序博客网 时间:2024/06/16 00:11
package po1;
import java.io.*;
import javax.swing.*;
public class Ioexercise1 {
    public static void main(String[] args) throws IOException {
       File file = null;
       JFileChooser fc = new JFileChooser(); // 创建一个文件选择器
       
       //打开文件,获得选择的文件名称
       fc.setDialogTitle("open"); // 设置标题
       if (fc.showOpenDialog(new JFrame()) == JFileChooser.APPROVE_OPTION) {// 如果选择了确定按钮,就获得选择的文件对象
           file = fc.getSelectedFile();   //file存放选取的文件对象
       }
 
       String fileAbsoPath = file.getAbsolutePath(); // 可以得到文件的绝对路径
       System.out.println(fileAbsoPath); // 输出路径
 
       // 创建输入流,读取文件,对文件内容进行处理
     
           String str="Hello World!"; //准备数据
           OutputStream os=new FileOutputStream(fileAbsoPath);
                          //创建文件输出流
           byte[] b=str.getBytes();   //准备写
           os.write(b);     //写出数据
           os.close();      //关闭输出流


       //…………………………
       //处理完毕
       
       //保存文件
       fc.setDialogTitle("保存文件");
       if (fc.showSaveDialog(new JFrame()) == JFileChooser.APPROVE_OPTION) {// 如果选择了确定按钮,就获得选择的文件对象
           file = fc.getSelectedFile();   //file存放选取的文件对象
       }
       //创建输出流,写文件内容
       
           InputStream is=new FileInputStream(fileAbsoPath);
                          //创建文件输入流
           byte[] b1=new byte[1024];   
           is.read(b1);      //读取数据
           is.close();      //关闭输入流
           System.out.println(new String(b1));
}
 
}
原创粉丝点击