io流的简单应用1



   首先创建出复制的界面:
  
public class FileCopy extends JFrame implements ActionListener{
	
	boolean bool = false;
	
	JTextField jtf = new JTextField();
	JTextField jti = new JTextField();
	
	public static void main(String[] args) {
		new FileCopy().FileUI();
	}
	
	public void FileUI(){
		this.setTitle("复制");
		this.setSize(400,400);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		this.setLayout(null);
		
		//添加JTextField和JLabel
		jtf.setBounds(40, 40, 200, 20);
		this.add(jtf);
		
		JLabel jlb = new JLabel("复制到");
		jlb.setBounds(55,80,40,40);
		this.add(jlb);
		

		jti.setBounds(40,130,200,20);
		this.add(jti);
		
		//添加复制按钮
		JButton jb = new JButton("复制");
		jb.setBounds(55, 200, 80, 40);
		jb.addActionListener(this);
		this.add(jb);
		
		//添加单选按钮
		JCheckBox jcb = new JCheckBox("覆盖");
		JCheckBox jcc = new JCheckBox("后续");
		jcc.setBounds(55, 280, 100, 40);
		jcb.setBounds(55, 250, 100, 40);
		jcb.setSelected(true);
		
		jcb.addActionListener(new Action());
		jcb.setActionCommand("覆盖");
		jcc.addActionListener(new Action());
		jcc.setActionCommand("后续");
		
		ButtonGroup group = new ButtonGroup();
		group.add(jcb);
		group.add(jcc);
		
		this.add(jcb);
		this.add(jcc);
		
		this.setVisible(true);
	}

      然后完成复制按钮的动作命令
     
public void actionPerformed(ActionEvent e) {
		String str1 = jtf.getText();
		String str2 = jti.getText();
		
		try {
			
			FileInputStream jfi = new FileInputStream(str1);
			FileOutputStream jfo = new FileOutputStream(str2,bool);
			
			BufferedInputStream bfs = new BufferedInputStream(jfi);
			BufferedOutputStream bos = new BufferedOutputStream(jfo);
			
			int a = bfs.available();
			byte[] b = new byte[a];
			
			bfs.read(b);
			
			bos.write(b);
			
			bos.flush();

			
			bos.close();
			bfs.close();
			
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
	}

     FileInputStream和FileOutputStream是文件字节输入输出流。通过文件路径进行相应的read和write,有两种方式:
     1.使用循环函数调用read()。
     2.使用read(Object[])来给一个数组赋值。(这时数组定义时可以使用int a = bfs.available();
byte[] b = new byte[a];)
     BufferedInputStream和BufferedOutputStream即缓冲输入以及支持 mark 和 reset 方法的能力。在创建 BufferedInputStream 时,会创建一个内部缓冲区数组。在读取或跳过流中的字节时,可根据需要从包含的输入流再次填充该内部缓冲区,一次填充多个字节。
     其中的flush()就是在文件写入的时候加快读写的速度,实现同步,以免未读取就关闭文件io流。
     
     添加是否覆盖的动作命令
     public class Action implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if("覆盖".equals(e.getActionCommand())){
bool = false;
}else if("后续".equals(e.getActionCommand())){
bool = true;
}

}
      }
      改变bool值,在构造FileInputStream时判断是否覆盖。
      在使用路径时不应出现单“\”,这是特殊含义。

猜你喜欢

转载自2548540761.iteye.com/blog/2160521