带你完成Java实战练习之简单的文件管理器 附完整实例代码

倒影年华 2021-08-19 10:49:30 浏览数 (2969)
反馈

有一些小伙伴在学习Java后,不知道要做什么可以检验一下自己的学习成果,下面我为大家分享一篇关于Java的实战小练习,完成一个简单的文件管理器。有兴趣的小伙伴可以一起来看这篇文章,也可以跟着一块实操。

示例图

在这里插入图片描述

可以在指定目录下实现文件的创建、文件夹的创建、文件的复制、粘贴、删除、重命名、返回上一级目录、以及不同设备之间文件的发送

完整代码

package com.atguitu.java;

public class FileDemo {
	public static void main(String[] args) {
		FileSystem fs = new FileSystem();
		fs.start();
	}
}
package com.atguitu.java;


import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class FileSystem {
	JFrame frame; // 窗口
	Container container; // 创中的容器对象
	JPanel jPanel; // 创建面板
	JButton btn1; // 创建按钮
	JButton btn2;
	JButton btn3;
	JButton btn4;
	JButton btn5;
	JButton btn6;
	JButton btn7;
	JButton btn8;
	JList fileList;// 列表框对象
	Vector<String> vector = new Vector<String>(); // 列表框内容
	String currentPath = "D:\"; // 当前显示路径
	String copyPath = null; // 待拷贝路径

	public FileSystem() {
		frame = new JFrame("文件管理器");
		frame.setBounds(200, 100, 800, 600); // 设置窗口大小和位置
		frame.setLayout(new BorderLayout());
		container = frame.getContentPane();
		jPanel = new JPanel(); // 创建面板
		jPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
		btn1 = new JButton("创建文件"); // 创建按钮
		btn2 = new JButton("创建文件夹");
		btn3 = new JButton("复制");
		btn4 = new JButton("粘贴");
		btn5 = new JButton("删除");
		btn6 = new JButton("重命名");
		btn7 = new JButton("返回上一级目录");
		btn8 = new JButton("发送");

		// 添加按钮事件
		btn1.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.out.println("创建文件");
				int i = 1;
				String temp = currentPath + "newFile" + i + ".txt";
				while (new File(temp).exists()) {
					i++;
					temp = currentPath + "newFile" + i + ".txt";
				}
				FileUtil.createFile(temp);
				refreshFileList();
			}
		});
		btn2.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.out.println("创建文件夹");
				int i = 1;
				String temp = currentPath + "newDir" + i;
				while (new File(temp).exists()) {
					i++;
					temp = currentPath + "newFile" + i;
				}
				FileUtil.createDir(temp);
				refreshFileList();
			}
		});
		btn3.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.out.println("复制");
				if (fileList.getSelectedValue() != null) {
					String selectFile = fileList.getSelectedValue().toString();
					if (new File(currentPath + selectFile).exists()) {
						copyPath = currentPath + selectFile;
					}
				}
			}
		});
		btn4.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.out.println("粘贴");
				System.out.println("copyPath:" + copyPath);
				System.out.println("currentPath:" + currentPath);
				if (copyPath != null) {
					if (new File(copyPath).isDirectory()) {
						try {
							FileUtil.copyDirectiory(copyPath, currentPath);
						} catch (IOException e1) {
							// TODO 自动生成的 catch 块
							e1.printStackTrace();
						}
					} else if (new File(copyPath).isFile()) {
						try {
							FileUtil.copyFile(copyPath, currentPath + copyPath.substring(copyPath.lastIndexOf("\")));
						} catch (IOException e1) {
							// TODO 自动生成的 catch 块
							e1.printStackTrace();
						}
					}
					refreshFileList();
				}

			}
		});
		btn5.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("删除");

				if (fileList.getSelectedValue() != null) {
					String selectFile = fileList.getSelectedValue().toString();
					// System.out.println(selectFile == null);
					System.out.println(currentPath + selectFile);
					if (new File(currentPath + selectFile).exists()) {
						FileUtil.deleteFileOrDir(currentPath + selectFile);
						refreshFileList();
					}
				}
			}
		});
		btn6.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.out.println("重命名");

				if (fileList.getSelectedValue() != null) {
					String newName = JOptionPane.showInputDialog("请输入修改的文件名");
					if (newName != null) {
						String selectFile = fileList.getSelectedValue().toString();
						if (new File(currentPath + selectFile).exists()) {
							FileUtil.renameFile(currentPath, selectFile, newName);
							refreshFileList();
						}
					}
				}
			}
		});
		btn7.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				String temp = currentPath.substring(0,
						currentPath.substring(0, currentPath.length() - 1).lastIndexOf("\") + 1);
				System.out.println(temp);
				File f = new File(temp);
				if (f.isDirectory()) {
					currentPath = temp;
					refreshFileList();
				}
			}
		});
		btn8.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// 发送文件
				String fileName = (String) fileList.getSelectedValue();
				if (fileName != null && fileName.endsWith(".txt")) {
					// 弹出输入IP地址的界面
					new IPFrame(currentPath + fileName);
				}
			}
		});
		
		// 面板中添加按钮
		jPanel.add(btn1);
		jPanel.add(btn2);
		jPanel.add(btn3);
		jPanel.add(btn4);
		jPanel.add(btn8);
		jPanel.add(btn5);
		jPanel.add(btn6);
		jPanel.add(btn7);
		jPanel.add(btn8);
		container.add(jPanel, BorderLayout.NORTH);

		fileList = new JList(vector);
		fileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		fileList.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				// TODO Auto-generated method stub
				if (e.getValueIsAdjusting()) {
					System.out.println(fileList.getSelectedValue());
				}
			}
		});
		fileList.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					String temp = currentPath + fileList.getSelectedValue();
					File f = new File(temp);
					if (f.isDirectory()) {
						currentPath = currentPath + fileList.getSelectedValue();
						refreshFileList();
					}
				}
			}
		});

		container.add(fileList, BorderLayout.CENTER);
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent arg0) {
				System.exit(1);
			}
		});
	}

	public void refreshFileList() {
		fileList.setBorder(BorderFactory.createTitledBorder(currentPath + "文件列表:"));
		vector = FileUtil.fileList(currentPath);
		fileList.setListData(vector);
	}

	public void start() {
		refreshFileList();
		frame.setVisible(true);
		//启动接收文件的线程
		new ReceiveThread().start();
	}

}
package com.atguitu.java;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;

public class FileUtil {

	// 创建文件
	public static boolean createFile(String destFileName) {
		File file = new File(destFileName);
		if (file.exists()) {
			System.out.println("创建文件" + destFileName + "失败,目标文件已存在!");
			return false;
		}
		if (destFileName.endsWith(File.separator)) {
			System.out.println("创建文件" + destFileName + "失败,目标文件错误!");
			return false;
		}
		if (!file.getParentFile().exists()) {
			System.out.println("目标文件所在目录不存在,准备创建它!");
			if (!file.getParentFile().mkdirs()) {
				System.out.println("创建目标文件所在目录失败!");
				return false;
			}
		}
		try {
			if (file.createNewFile()) {
				System.out.println("创建文件" + destFileName + "成功!");
				return true;
			} else {
				System.out.println("创建文件" + destFileName + "失败!");
				return false;
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("创建文件" + destFileName + "失败!" + e.getMessage());
			return false;
		}
	}

	// 创建文件夹
	public static boolean createDir(String destDirName) {
		File dir = new File(destDirName);
		if (dir.exists()) {
			System.out.println("文件夹创建" + destDirName + "失败,目标文件夹已经存在");
			return false;
		}
		if (!destDirName.endsWith(File.separator)) {
			destDirName = destDirName + File.separator;
		}
        
		if (dir.mkdirs()) {
			System.out.println("文件夹创建" + destDirName + "成功!");
			return true;
		} else {
			System.out.println("文件夹创建" + destDirName + "失败!");
			return false;
		}
	}
	// 删除文件
	public static boolean deleteFileOrDir(String path) {
		File dir = new File(path);
		boolean success = true;
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				success = deleteFileOrDir(dir.getAbsolutePath()+"\"+children[i]);
				if (!success) {
					return false;
				}
			}
			success = dir.delete();
		} else {
			success = dir.delete();
		}

		return success;
	}

	// 复制文件
	public static void copyFile(String sPath, String tPath) throws IOException {
		File sourceFile = new File(sPath);
		File targetFile = new File(tPath);
        
		FileInputStream input = new FileInputStream(sourceFile);
		BufferedInputStream inBuff = new BufferedInputStream(input);

		FileOutputStream output = new FileOutputStream(targetFile);
		BufferedOutputStream outBuff = new BufferedOutputStream(output);

		byte[] b = new byte[1024 * 5];
		int len;
		while ((len = inBuff.read(b)) != -1) {
			outBuff.write(b, 0, len);
		}

		outBuff.flush();

		inBuff.close();
		outBuff.close();
		output.close();
		input.close();
	}

	// 复制文件夹
	public static void copyDirectiory(String sDir, String tDir) throws IOException {
		(new File(tDir)).mkdirs();
		File[] file = (new File(sDir)).listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isFile()) {
				File sourceFile = file[i];
				File targetFile = new File(new File(tDir).getAbsolutePath() + File.separator + file[i].getName());
				copyFile(sourceFile.getAbsolutePath(), targetFile.getAbsolutePath());
			}
			if (file[i].isDirectory()) {
				String dir1 = sDir + "/" + file[i].getName();
				String dir2 = tDir + "/" + file[i].getName();
				copyDirectiory(dir1, dir2);
			}
		}
	}
	// 文件重命名
	public static void renameFile(String path, String oldname, String newname) {
		if (!oldname.equals(newname)) {
			File oldfile = new File(path + "/" + oldname);
			File newfile = new File(path + "/" + newname);
			if (!oldfile.exists()) {
				return;
			}
			if (newfile.exists())
				System.out.println(newname + "文件名已经存在!");
			else {
				oldfile.renameTo(newfile);
			}
		} else {
			System.out.println("文件名未发生改变");
		}
	}

	// 得到文件列表
	public static Vector<String> fileList(String path) {
		Vector<String> vector = new Vector<String>();
		File[] fl = new File(path).listFiles();
		for (int i = 0; i < fl.length; i++) {
			if (fl[i].isFile()) {
				vector.add(fl[i].getName());
			}
			else if (fl[i].isDirectory()) {
				vector.add(fl[i].getName() + "\");
			}
		}
		return vector;
	}

}
package com.atguitu.java;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class IPFrame extends JFrame{
	private JLabel lblIp;
	private JTextField txtIp;
	private JButton btnIp;
	private JLabel lblMyIp;
	
	private String fileName;
	
	public IPFrame(String fileName) {
		this.fileName = fileName;
		this.getContentPane().setLayout(null);
		
		lblIp = new JLabel("接收方IP");
		this.getContentPane().add(lblIp);
		lblIp.setBounds(20, 20, 60, 25);
		
		txtIp = new JTextField();
		this.getContentPane().add(txtIp);
		txtIp.setBounds(70, 20, 100, 25);
		
		btnIp = new JButton("发送");
		this.getContentPane().add(btnIp);
		btnIp.setBounds(180, 20, 80, 25);
		btnIp.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				//点击发送按钮时,会执行此方法
				SendThread sendThread = new SendThread(fileName, txtIp.getText());
				sendThread.start();
			}
		});
		
		this.setBounds(200, 100, 350, 140);
		this.setVisible(true);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	public JLabel getLblIp() {
		return lblIp;
	}

	public void setLblIp(JLabel lblIp) {
		this.lblIp = lblIp;
	}

	public JTextField getTxtIp() {
		return txtIp;
	}

	public void setTxtIp(JTextField txtIp) {
		this.txtIp = txtIp;
	}

	public JButton getBtnIp() {
		return btnIp;
	}

	public void setBtnIp(JButton btnIp) {
		this.btnIp = btnIp;
	}

	public JLabel getLblMyIp() {
		return lblMyIp;
	}

	public void setLblMyIp(JLabel lblMyIp) {
		this.lblMyIp = lblMyIp;
	}

	
}

package com.atguitu.java;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ReceiveThread extends Thread{
	@Override
	public void run() {
		try {
			ServerSocket server = new ServerSocket(6687);
			System.out.println("ServerSocket启动...");
			while (true) {
				Socket s = server.accept();
				System.out.println("连接成功!");
				InputStream inputStream=s.getInputStream();
		        File file = new File("E:/shiyan.txt");
		        String fileName = file.getName();
		        OutputStream outputstream = new FileOutputStream(file);
		        int length=0;
		        byte[] buff = new byte[4096];
		        while((length=inputStream.read(buff))!=-1) {
		        	outputstream.write(buff,0,length);
		        }
		        outputstream.close();
		        inputStream.close();
		        s.close();
		        server.close();
		        System.out.println("文件传输完毕!文件存储名称为:"+fileName);
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("启动失败...");
		}
	}
}
package com.atguitu.java;


import java.io.*;
import java.net.Socket;

public class SendThread extends Thread{
	private String filePath;
	private String ipAddress;
	
	public SendThread(String filePath) {
		super();
		this.filePath = filePath;
	}
	
	public SendThread(String filePath, String ipAddress) {
		super();
		this.filePath = filePath;
		this.ipAddress = ipAddress;
	}

	@Override
	public void run() {
		try{
			
			File file=new File(filePath);
			FileInputStream fileInputstream = new FileInputStream(file);
			Socket socket=new Socket(ipAddress, 6687);
			OutputStream outputStream=new DataOutputStream(socket.getOutputStream());
			if(!file.exists()){
				return;
			}else{
				String fileName = file.getName();
				long length = file.length();
				int len = 0;
				byte[] buff = new byte[4096];
				while((len = fileInputstream.read(buff))!=-1) {
					outputStream.write(buff,0,len);
				}
				System.out.println("开始发送文件,文件名称为:"+fileName+"  文件大小"+length);
				
				outputStream.close();
				socket.close();
				fileInputstream.close();
				
				System.out.println("发送文件完毕!");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

本篇关于Java实现简单的文件管理系统完整的实战练习过程的文章就介绍到此结束了,如果各位小伙伴们还觉得意犹未尽,想了解更多关于Java实战练习的内容,可以在W3Cschool主站内搜索Java实战相关内容,

0 人点赞