📄 bytedemo.java
字号:
//字节流读写演示
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class ByteDemo extends JFrame implements ActionListener
{
JPanel pnlMain;
JLabel lblSource,lblDest;
JTextField txtSource,txtDest;
JButton btnOpen,btnCopy;
//声明一个JFileChooser对象
JFileChooser fc;
//声明一个FileInputStream对象
FileInputStream fisSource;
//声明一个FileOutputStream对象
FileOutputStream fosDest;
//构造函数
public ByteDemo()
{
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
{
fisSource=new FileInputStream(txtSource.getText());
fosDest=new FileOutputStream(txtDest.getText());
int intTemp;
//以字节流方式从源文件读后写入到目标文件
while ((intTemp=fisSource.read())!=-1)
fosDest.write(intTemp);
fisSource.close();
fosDest.close();
JOptionPane.showMessageDialog(null,"文件复制成功!");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"文件操作失败!");
}
}
}
public static void main(String args[])
{
new ByteDemo();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -