热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

Java实战之简单的文件管理器

这篇文章主要介绍了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 vector = new Vector(); // 列表框内容
	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  fileList(String path) {
		Vector vector = new Vector();
		File[] fl = new File(path).listFiles();
		for (int i = 0; i 
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文件管理器内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


推荐阅读
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • macOS Big Sur全新设计大版本更新,10+个值得关注的新功能
    本文介绍了Apple发布的新一代操作系统macOS Big Sur,该系统采用全新的界面设计,包括图标、应用界面、程序坞和菜单栏等方面的变化。新系统还增加了通知中心、桌面小组件、强化的Safari浏览器以及隐私保护等多项功能。文章指出,macOS Big Sur的设计与iPadOS越来越接近,结合了去年iPadOS对鼠标的完善等功能。 ... [详细]
  • 64G iPad升级到iPadOS后,发现外置存储只能在苹果自带的文件app中显示,非官方app无法直接读取外置存储的内容。用户只能先使用自带文件app将文件复制到iPad上,再用程序读取。这种限制给用户带来了不便,而且操作过程中还存在拷贝不显示进度、容易失败、不能安全弹出等问题。 ... [详细]
  • Unity3D引擎的体系结构和功能详解
    本文详细介绍了Unity3D引擎的体系结构和功能。Unity3D是一个屡获殊荣的工具,用于创建交互式3D应用程序。它由游戏引擎和编辑器组成,支持C#、Boo和JavaScript脚本编程。该引擎涵盖了声音、图形、物理和网络功能等主题。Unity编辑器具有多语言脚本编辑器和预制装配系统等特点。本文还介绍了Unity的许可证情况。Unity基本功能有限的免费,适用于PC、MAC和Web开发。其他平台或完整的功能集需要购买许可证。 ... [详细]
  • 本文介绍了iOS开发中检测和解决内存泄漏的方法,包括静态分析、使用instruments检查内存泄漏以及代码测试等。同时还介绍了最能挣钱的行业,包括互联网行业、娱乐行业、教育行业、智能行业和老年服务行业,并提供了选行业的技巧。 ... [详细]
  • 概述H.323是由ITU制定的通信控制协议,用于在分组交换网中提供多媒体业务。呼叫控制是其中的重要组成部分,它可用来建立点到点的媒体会话和多点间媒体会议 ... [详细]
  • POCOCLibraies属于功能广泛、轻量级别的开源框架库,它拥有媲美Boost库的功能以及较小的体积广泛应用在物联网平台、工业自动化等领域。POCOCLibrai ... [详细]
  • 当google在搜索上很成功,并购youtube、发布gmail、进入手机、一统地图的时候,我们说google真伟大。当苹果在mp3领域一骑绝尘,iphone秒杀诺基亚,ipad打倒了电子 ... [详细]
  • 我一直都有记录信息的习惯,不知是从什么时候开始,大约是在工作后不久。如今还真有点庆幸从那时开始记了点东西,当然是电子版的,写 ... [详细]
  • 用了element-ui的dialog组件加上canvas来绘图,在老版本 ... [详细]
  • 交换机配置:intg100unshintvlani1ipadd192.168.56.177qstelseuser-iv4authaaaproinsshupl3qsshuserpyt ... [详细]
  • 1.webkit内核中的一些私有的meta标签,这些meta标签在开发webapp时起到非常重要的作用(1) ... [详细]
  • 1、DashAPI文档Dash是一个API文档浏览器,使用户可以使用离线功能即时搜索无数API。程序员使用Dash可访问iOS,MacOS, ... [详细]
  • 单位准备购买平板电脑(如mipad),为了进行无纸化办公, ... [详细]
  • 与.Net大师Jeffrey Richter面对面交流——TUP对话大师系列活动回顾(多图配详细文字)...
    与.Net大师JeffreyRichter面对面交流——TUP对话大师系列活动回顾(多图配文字)上周末很有幸参加了CSDN举行的TUP活动, ... [详细]
author-avatar
程武钢2011
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有