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文件管理器内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 浅谈javap命令拆解字节码文件

    目的拆解分析反编译字节码 解析成人能够理解的结构 ,然后再对字节码文件进一步分析 源代码 public class test { private static int classV =2; public static void main(String[] args) { classV =200; int localV =4; localV =400; } } 二进制 idea bin_ed插件查看. 看不懂 那就使用人能看的懂的汇编语言查看类文件结构和代码指令. javap 指令和选项 0:无选

  • java 如何读取远程主机文件

    我就废话不多说了,大家还是直接看代码吧~ package com.cloudtech.web.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import com.cloudtech.web.entity.Role; public class

  • Java定时调用.ktr文件的示例代码(解决方案)

    1.Maven依赖 <!-- Kettle --> <dependency> <groupId>pentaho-kettle</groupId> <artifactId>kettle-core</artifactId> <version>7.1.0.0-12</version> </dependency> <dependency> <groupId>pentaho-kettl

  • Java基础之文件概述

    一.基本概念和常识 下面,我们先介绍一些基本概念和常识,包括二进制思维.文件类型.文本文件的编码.文件系统和文件读写等. 1.1 二进制思维 为了透彻理解文件,我们首先要有一个二进制思维. 所有文件, 不论是可执行文件.图片文件.视频文件.Word文件.压缩文件.txt 文件,都没什么可神秘的,它们都是以0和1的二进制形式保存的.我们 所看到的图片.视频.文本,都是应用程序对这些二进制的解析结果. 作为程序员,我们应该有一个编辑器,能查看文件的二进制形式, 比如UltraEdit,它支持以十六进

  • Java IO流学习总结之文件传输基础

    一.Java IO流总览 二.File类 2.1 常用API package pkg1; import java.io.File; import java.io.IOException; /** * @author Administrator * @date 2021/4/2 */ public class FileDemo { public static void main(String[] args) { // 了解构造函数,可查看API File file = new File("d:\\

  • java自定义ClassLoader加载指定的class文件操作

    继承ClassLoader并且重写findClass方法就可以自定义一个类加载器,具体什么是类加载器以及类加载器的加载过程与顺序下次再说,下面给出一个小demo 首先定义一个类,比如MyTest,并且将其编译成class文件,然后放到一个指定的文件夹下面,其中文件夹的最后几层就是它的包名,这里我将这个编译好的类放到 : /Users/allen/Desktop/cn/lijie/MyTest.class package cn.lijie; public class MyTest { public

  • java中Servlet程序下载文件实例详解

    对于一些普通的文件下载,想必大家都会去点击默认的链接进行资料获取.效率慢是一个方面,有时候下载的过程并不顺序.在学习了python中的一些程序后,我们可以选择使用Servlet进行文件的下载.下面我们先就Servlet进行简单的说明,然后带来有关的下载文件代码实例. 1.说明 Servlet是Sun公司开发的用于交互式地浏览和生成数据,生成动态Web的技术.狭义的Servlet是指Java语言实现的一个接口.但一般情况下,我们把实现了Servlet接口的Java程序叫做Servlet 2.使用s

  • IntelliJ IDEA创建普通的Java 项目及创建 Java 文件并运行的教程

    最近突然看到这篇几年前随手记录的文章,居然浏览量那么高.看来很多小伙伴也开始从 Eclipse 转到 IDEA,这里为了让大家更好的掌握 IDEA 的使用,我建议大家可以看看下面这个 IDEA 教程. IDEA 教程:IntelliJ-IDEA-Tutorial 首先,确保 IDEA 软件正确安装完成,Java 开发工具包 JDK 安装完成. IntelliJ IDEA下载地址:https://www.jetbrains.com/idea/download/#section=windows JD

  • Java(TM) Platform SE binary 打开jar文件的操作

    直接用javaw.exe想打开aspectj-1.9.4.jar安装aspectJ 选Java™ Platform SE binary提示JVM虚拟机打不开 可能是java的配置出了点问题,这里不想重新去配置java,直接用cmd用指令打开 成功打开AspectJ安装程序开始安装 补充:Java(TM) pPlatform SE binary已停止工作(解决办法) 问题描述: Java™ pPlatform SE binary已停止工作解决办法 问题事件名称:APPCRASH 早起清理了一下电脑

  • Java 如何实现解压缩文件和文件夹

    一 前言 项目开发中,总会遇到解压缩文件的时候.比如,用户下载多个文件时,服务端可以将多个文件压缩成一个文件(例如xx.zip或xx.rar).用户上传资料时,允许上传压缩文件,服务端进行解压读取每一个文件. 基于通用性,以下介绍几种解压缩文件的方式,包装成工具类,供平时开发使用. 二 压缩文件 压缩文件,顾名思义,即把一个或多个文件压缩成一个文件.压缩也有2种形式,一种是将所有文件压缩到同一目录下,此种方式要注意文件重名覆盖的问题.另一种是按原有文件树结构进行压缩,即压缩后的文件树结构保持不变

  • java不解压直接读取压缩包中文件的实现方法

    前言 最近写了个上传压缩包,将压缩包中的图片保存的接口,所以翻了翻网上文件流操作的博客,总结了一个不用解压,直接读取文件的方法 上代码 @RequestMapping(value = "packageUpload") public void packageUpload(HttpServletRequest request, HttpServletResponse response) { File file = null; try { MultipartHttpServletReques

  • JavaWeb实现文件的上传与下载

    JavaWeb实现文件的上传与下载,供大家参考,具体内容如下 第一步:导包 导入commons-fileupload-1.3.3.jar和commons-io-2.4.jar两个依赖包 第二步:编写前端页面 1.提交页面 index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ tagl

随机推荐