Java实现把电脑的文件信息存入到txt文本及数据库中

5 篇文章 0 订阅

为啥做这个

在网上找了好久没找到,都是实时UI模式去点击去查看的。
然后就自己做了个,主要是实现了将本地的文件信息,包括文件的名字、路径、子文件、大小等存入txt文本以及数据库中。
其实主要是因为要做毕设- -

思路

主要idea点是树节点的方式去代表一个文件,然后用递归的思想去做。
没更新之前【没有代码规范】已经放到github上了
代码代码

代码

看代码:

  1. 首先是 node,也就是节点描述
package computer.saveinformation;

import java.io.File;

import javax.swing.Icon;
import javax.swing.filechooser.FileSystemView;

/**  

* Title: Node

* Description: 

* @author Zero_Hwa

* @date Apr 10, 2020  9:26:50 PM

*/  
public class Node {
	
	File file;
	File[] files;
	int count;
	String path;
	FileSystemView fsv = FileSystemView.getFileSystemView();
	
	File root = fsv.getFiles(fsv.getHomeDirectory(), true)[0];
	                                                                                                                       
	public Node() {
		this.file = root;
		/**
		 * 这里用fsv.getFiels好像不能get到各个磁盘,原因不明,直接用files.listFiles()可以。
		 */
//		files = fsv.getFiles(file, true);
		files = file.listFiles();
		count = files.length;
		path = this.file.getAbsolutePath();
	}
	public File[] getFiles() {
		return files;
	}
	public int getCount() {
		return count;
	}
	public String getPath() {
		return path;
	}
	public Node(File file) {
		this.file = file;
		files = fsv.getFiles(file, true);
		count = files.length;
		path = file.getAbsolutePath();
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return fsv.getSystemDisplayName(file);
	}
	/**
	 * 在系统文件浏览器中显示的文件、目录或文件夹的图标。
	 * @return
	 */
	public Icon getIcon() {						
        return fsv.getSystemIcon(file);
    }
	
}
  1. 然后是Connector,这个挺有用的,也是自己图个方便写的,可以看这个链接~
  2. 再然后是数据库的方法,包括新建表和插入
package computer.saveinformation;

import java.sql.ResultSet;
import java.sql.SQLException;

/**  

* <p>Title: SaveInMysql</p>  

* <p>Description: </p>  

* @author Zero_Hwa

* @date Apr 10, 2020  

*/  
public class SaveInMysql {
	public boolean newTable() throws SQLException{
		boolean isSuccessful;
		String sql = "create table if not exists "
				+ "computerInformation"
				+ "("
				+ "id int unsigned not null auto_increment primary key,"
				+ "name varchar(2000) comment '文件名', "
				+ "childFiles text comment '子文件名,用空格隔开',"
				+ "path text comment '绝对路径',"
				+ "size bigint unsigned comment '大小,文件夹不显示大小',"
				+ "isFile boolean comment 'false为文件夹,true为文件'"
//				+ "parentid int unsigned comment '父文件夹的id'"
				+ ");";
		Connector.executeConnect(sql);
		String sql2 = "select * from information_schema.TABLES "
				+ "where "
				+ "table_schema ='db_bishe' "
				+ "and table_name = 'computerinformation';";
		ResultSet rs  =Connector.queryConnect(sql2);
		isSuccessful = rs.next();
		rs.close();
		return isSuccessful;
	}
	public void insertInfo(String name,String[] childName,String path,long size,boolean isFile) {
		String headSql = "insert into computerInformation(name,childFiles,path,size,isFile) value(";
		StringBuffer insertSql = new StringBuffer(300);
		insertSql.append(headSql);
		insertSql.append("'"+name+"','");
		for (String string : childName) {
			insertSql.append(string+"  ");
		}
		insertSql.append("',");
		insertSql.append("'"+path+"',");
		insertSql.append(size+",");
		insertSql.append(isFile);
		insertSql.append(");");
		Connector.executeConnect(insertSql.toString());
	}
	
	
	
//	public boolean deleteData() {
//		String sql = "TRUNCATE TABLE 'computerInformation'";
//		
//	}
}
  1. 最后是主方法。先做的存到本地文件,然后完成数据库相关方法后,就把对应方法穿插进去。
package computer.saveinformation;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;

import javax.swing.filechooser.FileSystemView;

/**  

* Title: SaveInText

* Description: 

* @author Zero_Hwa

* @date Apr 10, 2020  9:23:57 PM

*/  
public class SaveInText {

	FileSystemView fsv = FileSystemView.getFileSystemView();
	static SaveInMysql sim = new SaveInMysql();
	String deleteSql = "TRUNCATE TABLE computerInformation;";

	public static void main(String[] args) {
		// 从根目录记录
		// Node root = new Node();
		// 测试F盘
		Node root = new Node(new File("F:\\"));
		StringBuffer information = new StringBuffer("(当前文件名)(子文件名)(当前文件绝对路径)(类型)(大小)");
		try {
			// 如果为 true,则将数据写入文件末尾处,而不是写入文件开始处。
			// 此处为false原因是每次新运行,都重新写一遍文件,而不是写在原文件后面
			FileWriter fw = new FileWriter("D:\\Java_learn\\Bishe\\src\\TestForF.txt", false);
			// \r\n是换行符号
			fw.write(information + "\r\n");
			fw.flush();
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			sim.newTable();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SaveInText sit = new SaveInText();
		sit.recursion(root);
		
		
		// String information;
		// String name;
		// String[] childrenName;
		// String path;
		// long size;
		// String StringOfSize;
	}

	public void recursion(Node node) {
		// System.out.println("start of recursion");
		// System.out.println("node节点:"+node.toString());
		StringBuffer information = new StringBuffer("(当前文件名)(子文件名)(当前文件绝对路径)(大小)");
		String name;
		File[] files;
		String path;
		// 用来存MySQL里
		long size2;
		String size;
		
		//如果是文件的话
		if (node.file.isFile()) {
			size2 = getFileSize(node.file);
			size = getSize(size2);
			name = getName(node);
			path = getPath(node);
			information = information.delete(0, information.length());
			information.append("(" + name + ")");
			information.append("(无子文件)");
			information.append("(" + path + ")");
			information.append("(文件)");
			information.append("(" + size + ")");
			// System.out.println(information.toString());

			try {
				writeTxt(information.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//写入数据库中
			 String[] childrenName = {"无子文件"};
			 //将转义字符前面在加个反斜杠,避免在MySQL里转义
			 path = path.replaceAll("\\\\", "\\\\\\\\");
			sim.insertInfo(name, childrenName, path, size2, true);
			
			//如果是文件夹的话
		} else if (node.file.isDirectory()) {
			// 原来用的node.file.isDirectory()
			// 或用!node.file.isFile()

			/**
			 * getDirectorySize会因为时间过长出错?
			 */
			// size = getSize(getDirectorySize(node.file));

			/**
			 * 这里改用file.toString直接输出
			 */

			// childrenName = getChildrenName(node);
			// for (String string : childrenName) {
			// System.out.println("chName:"+string);
			// }
			// childrenName = node.file.list();

			files = getChildren(node);
			// for (File file : getChildren(node) ) {
			// System.out.println(file);
			// }

			name = getName(node);
			path = getPath(node);
			information = information.delete(0, information.length());
			information.append("(" + name + ")");
			information.append("(");

			/**
			 * 这里改用file.toString直接输出
			 */
			// for (String cn : childrenName) {
			// information.append(cn + " ");
			// }
			 String[] childrenName = new String[files.length];
			 int i = 0;
			for (File file : files) {
				information.append(file.getName() + " ");
				childrenName[i++] = file.getName();
			}

			information.append(")");
			information.append("(" + path + ")");
			information.append("(文件夹)");
			information.append("(文件夹不显示大小)");
			// information.append("("+size+")");
			// System.out.println(information.toString());
			try {
				writeTxt(information.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			path = path.replaceAll("\\\\", "\\\\\\\\");
			sim.insertInfo(name, childrenName, path, 0, false);
			
			/**
			 * 直接用File
			 */
			// for (String string : childrenName) {
			// System.out.println(string);
			// recursion(new Node(new File(node.getPath() + "\\" + string)));
			// }
			for (File file : files) {
				recursion(new Node(file));
			}
		} else {
			System.out.println("judgement of file is error ");
		}
	}

	/**
	 * @param information
	 *            要输出的一行文件信息
	 * @throws IOException
	 *             抛出IO异常
	 */
	public void writeTxt(String information) throws IOException {
		// 如果为 true,则将数据写入文件末尾处,而不是写入文件开始处。

		// FileWriter fw = new
		// FileWriter("D:\\Java_learn\\Bishe\\src\\computerInformation.txt", true);

		// F盘测试
		FileWriter fw = new FileWriter("D:\\\\Java_learn\\\\Bishe\\\\src\\\\TestForF.txt", true);

		// \r\n是换行符号
		fw.write(information + "\r\n");
		fw.flush();
		fw.close();
	}

	public String getName(Node node) {
		return node.toString();
	}

	/**
	 * 本来用的返回String的,但是发现在计算机下一层get不了各个磁盘的名字 所以直接用了getFiles,在 Node里面换成了
	 * file.listFiles
	 * 
	 * @param node
	 * @return
	 */
	public File[] getChildren(Node node) {
		File[] files = node.getFiles();
		// String[] childrenName = new String[files.length];
		// int i = 0;
		// for (File file : files) {
		// childrenName[i] = file.getName();
		// System.out.println("childrenName[i]"+childrenName[i]);
		// i++;
		// System.out.println(file);
		// }
		return files;
	}

	public String getPath(Node node) {
		return node.getPath();
	}

	public long getDirectorySize(File f) throws NullPointerException {
		long directorySize = 0;
		File[] flie = f.listFiles();
		for (int i = 0; i < flie.length; i++) {
			if (flie[i].isDirectory()) {
				directorySize = directorySize + getDirectorySize(flie[i]);
			} else {
				directorySize = directorySize + flie[i].length();
			}
		}
		return directorySize;
	}

	public long getFileSize(File f) {
		return f.length();
	}

	int radix = 1024;
	public String getSize(long size) {
		if (size < radix) {
			return size + "B";
		} else if (size < radix * radix) {
			return ((float) size / 1024) + "K";
		} else if (size < radix * radix * radix) {
			return ((float) size / (1024 * 1024)) + "M";
		} else if (size < radix * radix * radix * radix) {
			return ((float) size / (radix * radix * radix)) + "G";
		}
		return "Error";
	}

}

成果

  1. 存到本地文件中
    在这里插入图片描述
  2. 存到数据库中【用的mysqlworkbench可视化】
    在这里插入图片描述

有什么意见或者疑问点可以私聊我哦。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值