Java基础之IO流
来源:互联网 发布:趋势科技杀毒软件 知乎 编辑:程序博客网 时间:2024/05/18 03:17
闲来无事,总结一下自己过去学过的东西,也夯实一下自己的基础,首先总结让我感觉编程就是NB的IO流。
先上图
在图中可以清楚地看到整个IO流体系,从大方向来说分为字节流和字符流(一般字符流传输文字,字节流传输照片视频等大文件),那我们分别来说:
字节流:
在我的理解中字节流算是IO流最开始的样子,因为其实字符流其实就是对字节流的封装,好,闲话少说,在IO流中不得不说的也是大家极易混淆的就是输入输出流,因为在文件流中其实是读出写入,这个是最容易混淆的一定的注意。
字节流与字符流的区别:
字符流处理的单元为2个字节的Unicode字符,分别操作字符、字符数组或字符串,而字节流处理单元为1个字节,操作字节和字节数组。所以字符流是由Java虚拟机将字节转化为2个字节的Unicode字符为单位的字符而成的,所以它对多国语言支持性比较好!如果是音频文件、图片、歌曲,就用字节流好点,如果是关系到中文(文本)的,用字符流好点
所有文件的储存是都是字节(byte)的储存,在磁盘上保留的并不是文件的字符而是先把字符编码成字节,再储存这些字节到磁盘。在读取文件(特别是文本文件)时,也是一个字节一个字节地读取以形成字节序列 字节流可用于任何类型的对象,包括二进制对象,而字符流只能处理字符或者字符串; 2. 字节流提供了处理任何类型的IO操作的功能,但它不能直接处理Unicode字符,而字符流就可以
字节流是最基本的,所有的InputStrem和OutputStream的子类都是,主要用在处理二进制数据,它是按字节来处理的 但实际中很多的数据是文本,又提出了字符流的概念,它是按虚拟机的encode来处理,也就是要进行字符集的转化 这两个之间通过InputStreamReader和OutputStreamWriter来关联,实际上是通过byte[]和String来关联 在实际开发中出现的汉字问题实际上都是在字符流和字节流之间转化不统一而造成的程序中的输入输出都是以流的形式保存的,流中保存的实际上全都是字节文件。
下边用字节流和字符流两种实现几个功能(顺便复习一下GUI):
文件复制:(红色部分为文件操作)
先上图
CopyFile
import javax.swing.*;import javax.swing.filechooser.FileSystemView;import java.awt.*;import java.awt.event.*;import java.io.*;import java.math.BigInteger;import java.util.*;import java.util.List;/** * Created by lenovo on 2017/10/25. */public class CopyFile extends JFrame { // http://blog.csdn.net/yczz/article/details/38761237 //打开文件选择框 private static JFileChooser fileChooser; //任务窗体 private static CopyFile copyFile; //选中的所有文件 private static List<List<File>> listFiles; //文件显示列表 private static List<JList> jLists; //文件复制用户自己链接对应关系面板 private static DataCorresponding dataCorresponding; //任务总量 private static BigInteger task; //进度条大小 private static int progressBarMax = 10000; //进度条最小变动量---由k变为mb static int minC = 0; private static int minChange = minC == 0 ? 1 : minC; //当前任务变化量 private static int nowChange = 0; public static void main(String[] args) { listFiles = new ArrayList<>(); jLists = new ArrayList<>(); //创建窗体 copyFile = new CopyFile(); //创建最底层面板 Panel basePanel = new Panel(); //创建选项卡面板 JTabbedPane jTabbedPane = new JTabbedPane(); //创建选项卡中的面板 JScrollPane jsp = new JScrollPane();//---考虑到组件太多决定将jTabPanel_1放入到jsp中 //垂直滚动条自动显示// jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); //水平滚动条总是隐藏// jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); JPanel jTabPanel_1 = new JPanel(); //为选项卡的操作页面设置布局 jTabPanel_1.setLayout(new BorderLayout()); //创建操作面板 JPanel operation = new JPanel(); //为操作面板设置布局 operation.setLayout(new GridLayout(3, 1)); //创建目标文件选择面板 JPanel filePanel = new JPanel(); filePanel.setBorder(BorderFactory.createTitledBorder("要复制的文件或者文件夹")); //为目标文件面板添加内容 setLayout(filePanel, new String[]{"添加文件", "添加文件夹", "移除项目", "清空列表"}, "file"); //将目标文件选择面板添加到操作面板中 operation.add(filePanel); //创建目标文件copy目的地面板 JPanel dirPanel = new JPanel(); dirPanel.setBorder(BorderFactory.createTitledBorder("复制到的文件目录")); //为目的地面板设置布局 dirPanel.setLayout(new BorderLayout()); //为目的地面板添加内容 setLayout(dirPanel, new String[]{"添加文件夹", "移除项目", "清空列表"}, "dir"); //将目的地面板添加到操作面板中 operation.add(dirPanel); //创建功能文件复制的参数及进度面板 JPanel operationConfig = new JPanel(); operationConfig.setBorder(BorderFactory.createTitledBorder("")); //为operationConfig面板设置布局--行数或这列数任意一个为零指行或者列不限 operationConfig.setLayout(new GridLayout(0, 1)); //创建功能参数面板 JPanel funConfig = new JPanel(); funConfig.setBorder(BorderFactory.createTitledBorder("参数设置")); //为funConfig面板设置布局--行数或这列数任意一个为零指行或者列不限 funConfig.setLayout(new GridLayout(0, 1)); //创建参数列表项面板 JPanel configItem_1 = new JPanel(); configItem_1.setLayout(new FlowLayout(FlowLayout.LEFT)); JLabel configMsg = new JLabel("目标目录下已有同名文件存在时:"); ButtonGroup btnGroup = new ButtonGroup(); JRadioButton jrb_1 = new JRadioButton("覆盖", false); JRadioButton jrb_2 = new JRadioButton("跳过", false); JRadioButton jrb_3 = new JRadioButton("询问", true); btnGroup.add(jrb_1); btnGroup.add(jrb_2); btnGroup.add(jrb_3); configItem_1.add(configMsg); configItem_1.add(jrb_1); configItem_1.add(jrb_2); configItem_1.add(jrb_3); //将参数列表项放入到funConfig面板 funConfig.add(configItem_1); //创建参数列表项面板 JPanel configItem_2 = new JPanel(); configItem_2.setLayout(new FlowLayout(FlowLayout.LEFT)); JCheckBox config_2jrb = new JCheckBox("复制时先清空(删除)目标文件夹中所有内容", false); configItem_2.add(config_2jrb); //将参数列表项放入到funConfig面板 funConfig.add(configItem_2); //创建参数列表项面板 JPanel configItem_3 = new JPanel(); configItem_3.setLayout(new FlowLayout(FlowLayout.LEFT)); JCheckBox config_3jrb = new JCheckBox("任务类型为移动", false); configItem_3.add(config_3jrb); //将参数列表项放入到funConfig面板 funConfig.add(configItem_3); //将功能参数面板添加到operationConfig面板上 operationConfig.add(funConfig); //创建参数列表项面板 JPanel configItem_4 = new JPanel(); configItem_4.setLayout(new FlowLayout(FlowLayout.LEFT)); JLabel configMsg4 = new JLabel("文件复制方式:"); ButtonGroup btnGroup4 = new ButtonGroup(); JRadioButton jrb_41 = new JRadioButton("一对一执行", true); JRadioButton jrb_42 = new JRadioButton("所有要复制的文件要在目标目录的每一项中复制一遍", false); JRadioButton jrb_43 = new JRadioButton("自己对应", false); jrb_43.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dataCorresponding = new DataCorresponding(listFiles, copyFile); copyFile.setVisible(false); } }); btnGroup4.add(jrb_41); btnGroup4.add(jrb_42); btnGroup4.add(jrb_43); configItem_4.add(configMsg4); configItem_4.add(jrb_41); configItem_4.add(jrb_42); configItem_4.add(jrb_43); //将参数列表项放入到funConfig面板 funConfig.add(configItem_4); //将功能参数面板添加到operationConfig面板上 operationConfig.add(funConfig); //创建功能执行进度面板 JPanel progessPanel = new JPanel(); progessPanel.setLayout(new GridLayout(1, 1)); progessPanel.setBorder(BorderFactory.createTitledBorder("功能执行进度")); //创建进度条 JProgressBar progressBar = new JProgressBar(); //设置进度条上是否有字符显示 progressBar.setStringPainted(true); //设置进度颜色 progressBar.setBackground(Color.GREEN); progressBar.setMaximum(progressBarMax); //将进度条添加到progessPanel面板中 progessPanel.add(progressBar); //将功能执行进度面板添加到operationConfig面板上 operationConfig.add(progessPanel); //将文件复制的参数及进度面板添加到操作面板中 operation.add(operationConfig); //将操作面板添加到jTabPanel_1中 jTabPanel_1.add(operation, BorderLayout.CENTER); //创建开始按钮 JButton start = new JButton("开始"); start.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { progressBar.setValue(0); //任务总量 task = new BigInteger("0");//divide这是除法 //读取各种配置 //目标目录下已有同名文件配置 int fileIsExist = 3; if (jrb_1.isSelected()) { //覆盖 fileIsExist = 1; } else if (jrb_2.isSelected()) { //跳过 fileIsExist = 2; } else { //询问 fileIsExist = 3; } //复制文件夹时是否先清空(删除)目标文件夹中的内容 boolean dirIsClear = config_2jrb.isSelected(); //任务类型为移动 boolean fileIsMove = config_3jrb.isSelected(); //文件复制方式 int fileCopyType = 1; if (jrb_41.isSelected()) { fileCopyType = 1; getTasks(listFiles, dirIsClear, fileIsMove, 1); //开始进行复制 startCopyFiles1Or2(listFiles.get(0), listFiles.get(1), progressBar, fileIsExist, dirIsClear, fileIsMove, 1); } else if (jrb_42.isSelected()) { fileCopyType = 2; getTasks(listFiles, dirIsClear, fileIsMove, 2); //开始进行复制 startCopyFiles1Or2(listFiles.get(0), listFiles.get(1), progressBar, fileIsExist, dirIsClear, fileIsMove, 2); } else { fileCopyType = 3; List<List<File>> correspondingFiles = dataCorresponding.getCorrespondingFiles(); getTasks(correspondingFiles, dirIsClear, fileIsMove, 3); //开始进行复制 startCopyFiles3(correspondingFiles, listFiles.get(1), progressBar, fileIsExist, dirIsClear, fileIsMove); } //递归求出任务总量// getFileOrDirSize(""); } }); //将开始按钮添加到jTabPanel_1中 jTabPanel_1.add(start, BorderLayout.SOUTH); //将选项卡中的面板添加到选项卡面板中 jsp.setViewportView(jTabPanel_1); jTabbedPane.addTab("操作文件", jsp); //创建选项卡中的面板 JPanel jTabPanel_2 = new JPanel(); JLabel msg = new JLabel(); msg.setText("联系QQ:3028889743"); jTabPanel_2.add(msg); //将选项卡中的面板添加到选项卡面板中 jTabbedPane.add("使用说明", jTabPanel_2); //为basePanel设置布局----这句必须有 basePanel.setLayout(new GridLayout(1, 1)); //将选项卡面板添加到basePanel中 basePanel.add(jTabbedPane); //将最底层面板添加到窗体中 copyFile.add(basePanel); //设置窗体可见 copyFile.setVisible(true); //设置窗体大小 copyFile.pack(); copyFile.setMinimumSize(new Dimension(800, 600)); //设置窗体居中 copyFile.setLocationRelativeTo(null); //设置窗体在点击关闭按钮时退出程序 copyFile.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); fileChooser = new JFileChooser(); FileSystemView fsv = FileSystemView.getFileSystemView(); fileChooser.setCurrentDirectory(fsv.getHomeDirectory()); fileChooser.setDialogTitle("请选择要上传的文件夹"); fileChooser.setApproveButtonText("确定"); } private static void getTasks(List<List<File>> listFiles, boolean dirIsClear, boolean fileIsMove, int fileCopyType) { //-------------BigInteger的Add方法不会改变自身的值会返回一个BigInteger的对象所以需要重新赋值------------- //获得任务总量 if (dirIsClear) { List<File> dirs = listFiles.get(1); for (int i = 0; i < dirs.size(); i++) { task = task.add(getFileOrDirSize(dirs.get(i).getPath())); } } if (fileCopyType == 3) { for (int i = 0; i < listFiles.size(); i++) { for (int j = 0; j < listFiles.get(i).size(); j++) { if (fileIsMove) { task = task.add(getFileOrDirSize(listFiles.get(i).get(j).getPath()).multiply(new BigInteger("2"))); } else { task = task.add(getFileOrDirSize(listFiles.get(i).get(j).getPath())); } } } } else { List<File> files = listFiles.get(0); String dirLne = listFiles.get(1).size() + ""; for (int i = 0; i < files.size(); i++) { if (fileIsMove) { if (fileCopyType == 1) { task = task.add(getFileOrDirSize(files.get(i).getPath()).multiply(new BigInteger("2"))); } else if (fileCopyType == 2) { task = task.add(getFileOrDirSize(files.get(i).getPath()).multiply(new BigInteger("2")).multiply(new BigInteger(dirLne))); } } else { if (fileCopyType == 1) { task = task.add(getFileOrDirSize(files.get(i).getPath())); } else if (fileCopyType == 2) { task = task.add(getFileOrDirSize(files.get(i).getPath()).multiply(new BigInteger(dirLne))); } } } } minC = task.divide(new BigInteger(progressBarMax / 100 + "").multiply(new BigInteger("1024")).multiply(new BigInteger("1024"))).intValue(); minChange = minC == 0 ? 1 : minC; showInList(jLists.get(1), "此次任务总量为:" + task.divide(new BigInteger("1024").multiply(new BigInteger("1024"))) + "MB"); } private static void startCopyFiles1Or2(List<File> files, List<File> dirs, JProgressBar progressBar, int fileIsExist, boolean dirIsClear, boolean fileIsMove, int fileCopyType) { new Thread(new Runnable() { @Override public void run() { if (dirIsClear) { for (int i = 0; i < dirs.size(); i++) { delAllFile(dirs.get(i).getPath()); } } for (int i = 0; i < dirs.size(); i++) { if (fileCopyType == 1) { if (files.get(i).isFile()) { copyFile(files.get(i).getPath(), dirs.get(i).getPath(), fileIsExist, progressBar); } else { copyFolder(files.get(i).getPath(), dirs.get(i).getPath() + "\\" + files.get(i).getName(), fileIsExist, progressBar); } } else { for (int j = 0; j < files.size(); j++) { if (files.get(j).isFile()) { copyFile(files.get(j).getPath(), dirs.get(i).getPath(), fileIsExist, progressBar); } else { copyFolder(files.get(j).getPath(), dirs.get(i).getPath() + "\\" + files.get(j).getName(), fileIsExist, progressBar); } } } } if (fileIsMove) { for (int i = 0; i < files.size(); i++) { if (files.get(i).isFile()) { delFile(files.get(i).getPath()); } else { delAllFile(files.get(i).getPath()); } } } progressBar.setValue(progressBarMax); showInList(jLists.get(1), "任务完成"); progressBar.setString("任务完成"); copyFile.pack(); } }).start(); } private static void startCopyFiles3(List<List<File>> files, List<File> dirs, JProgressBar progressBar, int fileIsExist, boolean dirIsClear, boolean fileIsMove) { new Thread(new Runnable() { @Override public void run() { if (dirIsClear) { for (int i = 0; i < dirs.size(); i++) { delAllFile(dirs.get(i).getPath()); } } for (int i = 0; i < files.size(); i++) { for (int j = 0; j < files.get(i).size(); j++) { if (files.get(i).get(j).isFile()) { copyFile(files.get(i).get(j).getPath(), dirs.get(i).getPath(), fileIsExist, progressBar); } else { copyFolder(files.get(i).get(j).getPath(), dirs.get(i).getPath() + "\\" + files.get(i).get(j).getName(), fileIsExist, progressBar); } } } if (fileIsMove) { for (int i = 0; i < files.size(); i++) { for (int j = 0; j < files.get(i).size(); j++) { if (files.get(i).get(j).isFile()) { delFile(files.get(i).get(j).getPath()); } else { delAllFile(files.get(i).get(j).getPath()); } } } } progressBar.setValue(progressBarMax); showInList(jLists.get(1), "任务完成"); progressBar.setString("任务完成"); } }).start(); } private static void setLayout(JPanel panel, String[] functions, String type) { java.util.List<File> files = new ArrayList<>(); //面板设置布局 panel.setLayout(new BorderLayout()); //创建显示所选文件或者文件夹的目录面板 JList fileList = new JList(); //一次只能选择一项// list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //可以按住Ctrl或者Shift键多选 fileList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); //可以按住Ctrl或者Shift键多选,但是当按住Ctrl选择时只能选相邻的// list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); JScrollPane fileListPanel = new JScrollPane(fileList); //将fileListPanel面板添加到Panel面板中 panel.add(fileListPanel, BorderLayout.CENTER); //创建功能按钮面板 JPanel functionButtons = new JPanel(); //为filesButton设置布局 functionButtons.setLayout(new GridLayout(0, 1)); for (int i = 0; i < functions.length; i++) { int index = i; JButton functionBtn = new JButton(functions[i]); functionBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int result = -100; DefaultListModel listModel; if (type.equals("file")) { //可以做一个判断----判断当前所选文件是否已经包含在已选中的文件列表中(先判断是否包含当前路径,如果包含再去判断是否包含此文件比如已有目录E:\ 那么E:\dir就不需要再次添加) switch (functions[index]) { case "添加文件": fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); result = fileChooser.showOpenDialog(copyFile); if (result == JFileChooser.APPROVE_OPTION) {// System.out.println(fileChooser.getSelectedFile().getPath()); File file = fileChooser.getSelectedFile(); files.add(file); showInList(fileList, "[文 件]" + file.getName()); } break; case "添加文件夹": addDir(fileList, files); break; case "移除项目": listModel = (DefaultListModel) fileList.getModel(); removeItem(listModel, fileList, files); break; case "清空列表": listModel = (DefaultListModel) fileList.getModel(); listModel.clear(); fileList.setModel(listModel); files.clear(); break; } } else { switch (functions[index]) { case "添加文件夹": addDir(fileList, files); break; case "移除项目": listModel = (DefaultListModel) fileList.getModel(); removeItem(listModel, fileList, files); break; case "清空列表": listModel = (DefaultListModel) fileList.getModel(); listModel.clear(); fileList.setModel(listModel); files.clear(); break; } } } }); functionButtons.add(functionBtn); } //将文件选取功能按钮面板添加到Panel面板 panel.add(functionButtons, BorderLayout.EAST); //将目录面板放到jList中 jLists.add(fileList); //将目录项放到listFiles中 listFiles.add(files); } private static void addDir(JList fileList, java.util.List<File> files) { fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int result = fileChooser.showOpenDialog(copyFile); if (result == JFileChooser.APPROVE_OPTION) {// System.out.println(fileChooser.getSelectedFile().getPath()); File file = fileChooser.getSelectedFile(); files.add(file); showInList(fileList, "[文件夹]" + file.getName()); } } private static void removeItem(DefaultListModel listModel, JList fileList, java.util.List<File> files) { int[] list = fileList.getSelectedIndices(); for (int i = 0; i < list.length; i++) { listModel.remove(list[i] - i); files.remove(list[i] - i); } fileList.setModel(listModel); } private static void showInList(JList fileList, String fileName) { //更新UI必须在主线程中进行 SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (0 == fileList.getModel().getSize()) { //新建一个默认项集合 DefaultListModel listModel = new DefaultListModel(); //操作这个集合 listModel.add(0, fileName); //将这个集合添加到JList中 fileList.setModel(listModel); } //JList的项不为空时 else { //从JList中获得这个集合,转换为默认项集合类型 DefaultListModel listModel = (DefaultListModel) fileList.getModel(); //追加元素 listModel.add(listModel.getSize(), fileName); //将这个集合添加到JList中 fileList.setModel(listModel); } } }); } //获得文件(夹)的大小 public static BigInteger getFileOrDirSize(String filePath) { File f = new File(filePath); BigInteger bigInteger = new BigInteger("0"); if (f.exists() && f.isFile()) { String len = f.length() + ""; bigInteger = bigInteger.add(new BigInteger(len)); } else if (f.exists() && f.isDirectory()) { String[] fl = f.list(); for (int i = 0; i < fl.length; i++) { if (filePath.endsWith(File.separator)) {//为了跨平台File.separator相当于'\' bigInteger = bigInteger.add(getFileOrDirSize(filePath + fl[i])); } else { bigInteger = bigInteger.add(getFileOrDirSize(filePath + File.separator + fl[i])); } } } return bigInteger; } //复制单个文件 public static void copyFile(String oldPath, String newPath, int fileIsExist, JProgressBar progressBar) { try { File oldfile = new File(oldPath); File newFile = new File(newPath + "\\" + oldfile.getName()); if (newFile.exists() && newFile.isFile()) { //文件存在时 if (fileIsExist == 1) { copyFile(oldPath, newPath + "\\" + oldfile.getName(), progressBar); } else if (fileIsExist == 2) { double proportion = getFileOrDirSize(oldPath).divide(task).doubleValue(); progressBar.setValue(progressBar.getValue() + (int) (proportion * progressBarMax)); return; } else { int res = JOptionPane.showConfirmDialog(null, oldfile + "已存在(点击否会创建新名字的文件,点击×会跳过)", "是否覆盖", JOptionPane.YES_NO_OPTION); if (res == JOptionPane.YES_OPTION) { //点击“是”后执行这个代码块 copyFile(oldPath, newPath + "\\" + oldfile.getName(), progressBar); } else if (res == -1) { //点击×执行的代码 double proportion = getFileOrDirSize(oldPath).divide(task).doubleValue(); progressBar.setValue(progressBar.getValue() + (int) (proportion * progressBarMax)); return; } else { //点击“否”后执行这个代码块 copyFile(oldPath, newPath + "\\" + oldfile.getName() + new Date().toString(), progressBar); } } } else { copyFile(oldPath, newPath + "\\" + oldfile.getName(), progressBar); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } } private static void copyFile(String oldPath, String newPath, JProgressBar progressBar) { try { int bytesum = 0; int byteread = 0; InputStream inStream = new FileInputStream(oldPath); //读入原文件 FileOutputStream fs = new FileOutputStream(new File(newPath)); byte[] buffer = new byte[1024]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数 文件大小 fs.write(buffer, 0, byteread); nowChange++; if (nowChange >= minChange && progressBar.getValue() != progressBarMax - 1) { progressBar.setValue(progressBar.getValue() + 1); nowChange = 0; } } showInList(jLists.get(1), oldPath + "复制完成"); fs.close(); inStream.close(); } catch (IOException e) { showInList(jLists.get(1), oldPath + "复制出错!!!"); System.out.println(e); } } //复制整个文件夹内容 public static void copyFolder(String oldPath, String newPath, int fileIsExist, JProgressBar progressBar) { try { File oldfile = new File(oldPath); File newFile = new File(newPath + "\\" + oldfile.getName()); if (newFile.exists() && newFile.isDirectory()) { if (fileIsExist == 1) { copyFolder(oldPath, newPath, progressBar); } else if (fileIsExist == 2) { double proportion = getFileOrDirSize(oldPath).divide(task).doubleValue(); progressBar.setValue(progressBar.getValue() + (int) (proportion * progressBarMax)); return; } else { int res = JOptionPane.showConfirmDialog(null, oldPath + "已存在(点击否会创建新名字的文件,点击×会跳过)", "是否覆盖", JOptionPane.YES_NO_OPTION); if (res == JOptionPane.YES_OPTION) { //点击“是”后执行这个代码块 copyFolder(oldPath, newPath, progressBar); } else if (res == -1) { //点击×执行的代码 double proportion = getFileOrDirSize(oldPath).divide(task).doubleValue(); progressBar.setValue(progressBar.getValue() + (int) (proportion * progressBarMax)); return; } else { //点击“否”后执行这个代码块 copyFolder(oldPath, newPath + new Date().toString(), progressBar); } } } else { copyFolder(oldPath, newPath, progressBar); } } catch (Exception e) { showInList(jLists.get(1), oldPath + ",复制整个文件夹内容操作出错!!!"); e.printStackTrace(); } } public static void copyFolder(String oldPath, String newPath, JProgressBar progressBar) { try { (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹 File a = new File(oldPath); String[] file = a.list(); File temp = null; for (int i = 0; i < file.length; i++) { if (oldPath.endsWith(File.separator)) {//为了跨平台File.separator相当于'\' temp = new File(oldPath + file[i]); } else { temp = new File(oldPath + File.separator + file[i]); } if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString()); byte[] b = new byte[1024 * 5]; int len; while ((len = input.read(b)) != -1) { output.write(b, 0, len); nowChange += 5; if (nowChange >= minChange && progressBar.getValue() != progressBarMax - 1) { progressBar.setValue(progressBar.getValue() + 1); nowChange = 0; } } output.flush(); output.close(); input.close(); } if (temp.isDirectory()) {//如果是子文件夹 copyFolder(oldPath + "\\" + file[i], newPath + "\\" + file[i], progressBar); } showInList(jLists.get(1), temp + "复制完成"); } showInList(jLists.get(1), oldPath + "复制完成"); } catch (IOException e) { showInList(jLists.get(1), oldPath + ",复制出错!!!"); } } //删除文件夹里面的所有文件 public static void delAllFile(String path) { File file = new File(path); if (!file.exists()) { return; } if (!file.isDirectory()) { return; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path + "\\" + tempList[i]);//先删除文件夹里面的文件 delFolder(path + "\\" + tempList[i]);//再删除空文件夹 } } java.io.File myFilePath = new java.io.File(path); myFilePath.delete(); } //删除文件夹 public static void delFolder(String folderPath) { try { delAllFile(folderPath); //删除完里面所有内容 String filePath = folderPath; filePath = filePath.toString(); java.io.File myFilePath = new java.io.File(filePath); myFilePath.delete(); //删除空文件夹 } catch (Exception e) { System.out.println("删除文件夹操作出错"); e.printStackTrace(); } } //删除单个文件 public static void delFile(String filePathAndName) { try { String filePath = filePathAndName; filePath = filePath.toString(); java.io.File myDelFile = new java.io.File(filePath); myDelFile.delete(); } catch (Exception e) { System.out.println("删除文件操作出错"); e.printStackTrace(); } }}
DataCorresponding
import javax.swing.*;import javax.swing.table.DefaultTableModel;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.util.ArrayList;import java.util.List;/** * Created by lenovo on 2017/10/27. */public class DataCorresponding { //放置目的地目录中对应要存入的目标文件 private List<List<File>> correspondingFiles; private List<String> row_index1_2; private JTable corrTable; public DataCorresponding(List<List<File>> listFiles,CopyFile copyFile){ correspondingFiles=new ArrayList<>(); row_index1_2=new ArrayList<>(); List<String> filesName0=new ArrayList<>(); List<String> filesName1=new ArrayList<>(); for(int i=0;i<listFiles.get(1).size();i++){ correspondingFiles.add(new ArrayList<>()); filesName1.add(listFiles.get(1).get(i).getName()); } for(int i=0;i<listFiles.get(0).size();i++){ filesName0.add(listFiles.get(0).get(i).getName()); } //创建窗体 JFrame corrWindow=new JFrame("将文件与目录对应"); //创建窗体最底层面板 JPanel basePanel=new JPanel(); //为basePanel设置布局 basePanel.setLayout(new BorderLayout()); //创建列表展示模板 JPanel showFiles=new JPanel(); //创建列表展示项 JLabel jcb2Label=new JLabel("目的地目录:"); JComboBox jcb2 = new JComboBox(filesName1.toArray()); //将列表展示项添加到showFiles面板中 showFiles.add(jcb2Label); showFiles.add(jcb2); //创建列表展示项 JLabel jcb1Label=new JLabel("目标文件:"); JComboBox jcb1 = new JComboBox(filesName0.toArray()); //将列表展示项添加到showFiles面板中 showFiles.add(jcb1Label); showFiles.add(jcb1); //创建确定按钮 JButton jbtn = new JButton("确定"); jbtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int index2=jcb2.getSelectedIndex(); int index1=jcb1.getSelectedIndex(); correspondingFiles.get(index2).add(listFiles.get(0).get(index1)); DefaultTableModel model=(DefaultTableModel) corrTable.getModel(); model.addRow(new Object[] { listFiles.get(1).get(index2).getName(), listFiles.get(0).get(index1).getName()}); corrTable.setModel(model); row_index1_2.add(index1+"==="+index2); } }); //将确定按钮添加到showFiles面板中 showFiles.add(jbtn); //创建删除按钮 JButton jbtnd = new JButton("删除"); jbtnd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selectedRow = corrTable.getSelectedRow();//获得选中行的索引 if(selectedRow!=-1) //存在选中行 { ((DefaultTableModel)corrTable.getModel()).removeRow(selectedRow); //删除行 String[] index1_2=row_index1_2.get(selectedRow).split("==="); correspondingFiles.get(Integer.parseInt(index1_2[1])).remove(listFiles.get(0).get(Integer.parseInt(index1_2[0]))); row_index1_2.remove(selectedRow); } } }); //将删除按钮添加到showFiles面板中 showFiles.add(jbtnd); //将showFiles面板添加到basePanel面板 basePanel.add(showFiles,BorderLayout.NORTH); //创建对应关系面板 JScrollPane corrPanel; //创建表格存放对应关系(用GridLayout或者JList也不错) //创建表头 String[] columnNames = {"目的地目录","目标文件"}; //表内容 String[][] datas = {}; DefaultTableModel model = new DefaultTableModel(datas, columnNames); corrTable = new JTable(model){ public boolean isCellEditable(int row, int column) { return false;//表格不允许被编辑 } }; //设置表格填充整个视图,在默认情况下,如果表格的大小小于视图(窗体) corrTable.setFillsViewportHeight(true); //将corrTable添加到corrPanel面板中 corrPanel=new JScrollPane(corrTable); //将corrPanel面板添加到basePanel中 basePanel.add(corrPanel,BorderLayout.CENTER); //创建提交面板 JPanel submitPanel=new JPanel(); //为提交面板设置布局 submitPanel.setLayout(new GridLayout(1,1)); //创建提交按钮 JButton submitBtn=new JButton("提交"); submitBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { corrWindow.setVisible(false); copyFile.setVisible(true); } }); //将提交按钮添加到submitPanel面板中 submitPanel.add(submitBtn); //将corrPanel面板添加到basePanel中 basePanel.add(submitPanel,BorderLayout.SOUTH); //将最底层面板添加到corrWindow中 corrWindow.add(basePanel); //设置窗体可见 corrWindow.setVisible(true); //设置窗体大小 corrWindow.pack(); corrWindow.setMinimumSize(new Dimension(800,600)); //设置窗体居中 corrWindow.setLocationRelativeTo(null); } public List<List<File>> getCorrespondingFiles() { return correspondingFiles; } public void setCorrespondingFiles(List<List<File>> correspondingFiles) { this.correspondingFiles = correspondingFiles; }}IO流详细介绍
- java基础之 IO流
- Java基础之IO流
- Java基础之IO流
- Java基础之IO流
- Java基础之IO流
- JAVA基础之IO流
- java基础之IO流
- java基础之io流
- java基础之io流
- Java基础之IO流
- java基础之IO流
- Java基础之IO流
- Java基础之IO流
- java基础之io
- java基础之IO
- java基础之IO
- java基础之IO
- Java基础之IO
- 值比较 跟 索引比较
- Redis官方文档(入门必备)
- Matlab GUI,颜色对话框,设置按钮背景颜色
- Hadoop HDFS本地存储目录结构解析
- C++实现一个String类
- Java基础之IO流
- 自定义注解设置缓存有效期的正确姿势
- jvm参数调优
- 关于使用chrome扩展插件
- IFE-TASK17(任务十七:零基础JavaScript编码(五))
- Matlab GUI,进度条(waitbar)
- 设计模式(12)--外观模式
- connector.ClientAbortException: java.io.IOException: 您的主机中的软件中止了一个已建立的连接
- py 查看一个文件夹下的文件数量