⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 characterdemo.java

📁 学习参考,java基本语法练习,包括一些常用的技巧
💻 JAVA
字号:
//字符流读写演示
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class CharacterDemo extends JFrame implements ActionListener
{
	JPanel pnlMain;
	JLabel lblSource,lblDest;
	JTextField txtSource,txtDest;
	JButton btnOpen,btnCopy;
	//声明一个JFileChooser对象
	JFileChooser fc;
	//声明一个FileReader对象
	FileReader frSource;
	//声明一个FileWriter对象	
	FileWriter fwDest;
	//构造函数
	public CharacterDemo()
	{
		super("字符方式读写文件演示");
		fc=new JFileChooser();
		pnlMain=new JPanel(new GridLayout(3,2));
		lblSource=new JLabel("源文件:");
		lblDest=new JLabel("目标文件:");
		txtSource=new JTextField(10);
		txtDest=new JTextField(10);
		btnOpen=new JButton("打开");
		btnOpen.addActionListener(this);
		btnCopy=new JButton("复制");
		btnCopy.setEnabled(false);
		btnCopy.addActionListener(this);
		pnlMain.add(lblSource);
		pnlMain.add(txtSource);
		pnlMain.add(lblDest);
		pnlMain.add(txtDest);
		pnlMain.add(btnOpen);
		pnlMain.add(btnCopy);
		setContentPane(pnlMain);
		setSize(250,150);
		setVisible(true);
	}
	//"打开"文件和"复制"文件事件处理
	public void actionPerformed(ActionEvent ae)
	{
		if (ae.getSource()==btnOpen)
			{
				int intRetVal=fc.showOpenDialog(this);
				if (intRetVal==JFileChooser.APPROVE_OPTION)
					{
						//打开文件名添加到源文件文本框
						txtSource.setText(fc.getSelectedFile().toString());
						//将"复制"按钮设置为可用
						btnCopy.setEnabled(true);
					}
			}
		else if (ae.getSource()==btnCopy)
		{
			copyFileByByte();
		}			
	}
	public void copyFileByByte()
	{
		//在源文件名和目标文件名都存在的条件下开始复制
		if (!txtSource.getText().equals(null) && !txtDest.getText().equals(null))
		{
			try
			{
				frSource=new FileReader(txtSource.getText());
				fwDest=new FileWriter(txtDest.getText());
				int intTemp;
				//以字符流方式从源文件读后写入到目标文件
				while ((intTemp=frSource.read())!=-1)
					fwDest.write(intTemp);
				frSource.close();
				fwDest.close();
				JOptionPane.showMessageDialog(null,"文件复制成功!");
			}catch(Exception e)
			{
				JOptionPane.showMessageDialog(null,"文件操作失败!");
			}
		}		
	}
	public static void main(String args[])
	{
		new CharacterDemo();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -