App下載

帶你完成Java實戰(zhàn)練習(xí)之簡單的文件管理器 附完整實例代碼

倒影年華 2021-08-19 10:49:30 瀏覽數(shù) (2749)
反饋

有一些小伙伴在學(xué)習(xí)Java后,不知道要做什么可以檢驗一下自己的學(xué)習(xí)成果,下面我為大家分享一篇關(guān)于Java的實戰(zhàn)小練習(xí),完成一個簡單的文件管理器。有興趣的小伙伴可以一起來看這篇文章,也可以跟著一塊實操。

示例圖

在這里插入圖片描述

可以在指定目錄下實現(xiàn)文件的創(chuàng)建、文件夾的創(chuàng)建、文件的復(fù)制、粘貼、刪除、重命名、返回上一級目錄、以及不同設(shè)備之間文件的發(fā)送

完整代碼

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; // 創(chuàng)中的容器對象
	JPanel jPanel; // 創(chuàng)建面板
	JButton btn1; // 創(chuàng)建按鈕
	JButton btn2;
	JButton btn3;
	JButton btn4;
	JButton btn5;
	JButton btn6;
	JButton btn7;
	JButton btn8;
	JList fileList;// 列表框?qū)ο?	Vector<String> vector = new Vector<String>(); // 列表框內(nèi)容
	String currentPath = "D:\"; // 當前顯示路徑
	String copyPath = null; // 待拷貝路徑

	public FileSystem() {
		frame = new JFrame("文件管理器");
		frame.setBounds(200, 100, 800, 600); // 設(shè)置窗口大小和位置
		frame.setLayout(new BorderLayout());
		container = frame.getContentPane();
		jPanel = new JPanel(); // 創(chuàng)建面板
		jPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
		btn1 = new JButton("創(chuàng)建文件"); // 創(chuàng)建按鈕
		btn2 = new JButton("創(chuàng)建文件夾");
		btn3 = new JButton("復(fù)制");
		btn4 = new JButton("粘貼");
		btn5 = new JButton("刪除");
		btn6 = new JButton("重命名");
		btn7 = new JButton("返回上一級目錄");
		btn8 = new JButton("發(fā)送");

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

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.out.println("創(chuàng)建文件");
				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("創(chuàng)建文件夾");
				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("復(fù)制");
				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) {
				// 發(fā)送文件
				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 {

	// 創(chuàng)建文件
	public static boolean createFile(String destFileName) {
		File file = new File(destFileName);
		if (file.exists()) {
			System.out.println("創(chuàng)建文件" + destFileName + "失敗,目標文件已存在!");
			return false;
		}
		if (destFileName.endsWith(File.separator)) {
			System.out.println("創(chuàng)建文件" + destFileName + "失敗,目標文件錯誤!");
			return false;
		}
		if (!file.getParentFile().exists()) {
			System.out.println("目標文件所在目錄不存在,準備創(chuàng)建它!");
			if (!file.getParentFile().mkdirs()) {
				System.out.println("創(chuàng)建目標文件所在目錄失敗!");
				return false;
			}
		}
		try {
			if (file.createNewFile()) {
				System.out.println("創(chuàng)建文件" + destFileName + "成功!");
				return true;
			} else {
				System.out.println("創(chuàng)建文件" + destFileName + "失??!");
				return false;
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("創(chuàng)建文件" + destFileName + "失??!" + e.getMessage());
			return false;
		}
	}

	// 創(chuàng)建文件夾
	public static boolean createDir(String destDirName) {
		File dir = new File(destDirName);
		if (dir.exists()) {
			System.out.println("文件夾創(chuàng)建" + destDirName + "失敗,目標文件夾已經(jīng)存在");
			return false;
		}
		if (!destDirName.endsWith(File.separator)) {
			destDirName = destDirName + File.separator;
		}
        
		if (dir.mkdirs()) {
			System.out.println("文件夾創(chuàng)建" + destDirName + "成功!");
			return true;
		} else {
			System.out.println("文件夾創(chuàng)建" + 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;
	}

	// 復(fù)制文件
	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();
	}

	// 復(fù)制文件夾
	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 + "文件名已經(jīng)存在!");
			else {
				oldfile.renameTo(newfile);
			}
		} else {
			System.out.println("文件名未發(fā)生改變");
		}
	}

	// 得到文件列表
	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("發(fā)送");
		this.getContentPane().add(btnIp);
		btnIp.setBounds(180, 20, 80, 25);
		btnIp.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				//點擊發(fā)送按鈕時,會執(zhí)行此方法
				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("開始發(fā)送文件,文件名稱為:"+fileName+"  文件大小"+length);
				
				outputStream.close();
				socket.close();
				fileInputstream.close();
				
				System.out.println("發(fā)送文件完畢!");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

本篇關(guān)于Java實現(xiàn)簡單的文件管理系統(tǒng)完整的實戰(zhàn)練習(xí)過程的文章就介紹到此結(jié)束了,如果各位小伙伴們還覺得意猶未盡,想了解更多關(guān)于Java實戰(zhàn)練習(xí)的內(nèi)容,可以在W3Cschool主站內(nèi)搜索Java實戰(zhàn)相關(guān)內(nèi)容,

0 人點贊