Java文件操作之按行读取文件和遍历目录的方法
程序员文章站
2024-03-09 16:56:47
按行读取文件
package test;
import java.io.*;
import java.util.*;
public cla...
按行读取文件
package test; import java.io.*; import java.util.*; public class readtest { public static list<string> first_list; public static list<string> second_list; public readtest() { first_list = new linkedlist<>(); second_list = new linkedlist<>(); } public static void readfile() { final string filename = "d://aa.txt"; string str = null; int i = 0; try { linenumberreader reader = null; reader = new linenumberreader(new filereader(filename)); while ((str = reader.readline()) != null) { if (!str.isempty()) { string values[] = str.split(" "); first_list.add(values[0]); second_list.add(values[1]); } } } catch (ioexception e) { e.printstacktrace(); } } public static void main(string args[]) { readtest reader = new readtest(); reader.readfile(); for (int i = 0; i < first_list.size(); i++) { system.out.println(first_list.get(i) + ":" + second_list.get(i)); } } }
递归遍历目录
class listfiles{ public static arraylist filelist = new arraylist(); public static void listfiles(string dir){ file file = new file(dir); file[] files = file.listfiles(); if(null == files){ return; } for(int i = 0; i < files.length; i++){ if(files[i].isdirectory()) { listfiles(files[i].getabsolutepath()); } else{ system.out.println(files[i]); filelist.add(files[i]); } } } }
上面遍历目录是一种递归的方法,我们再来看一下非递归的实现:
//非递归 public static void scandirnorecursion(string path){ linkedlist list = new linkedlist(); file dir = new file(path); file file[] = dir.listfiles(); for (int i = 0; i < file.length; i++) { if (file[i].isdirectory()) list.add(file[i]); else{ system.out.println(file[i].getabsolutepath()); num++; } } file tmp; while (!list.isempty()) { tmp = (file)list.removefirst();//首个目录 if (tmp.isdirectory()) { file = tmp.listfiles(); if (file == null) continue; for (int i = 0; i < file.length; i++) { if (file[i].isdirectory()) list.add(file[i]);//目录则加入目录列表,关键 else{ system.out.println(file[i]); num++; } } } else { system.out.println(tmp); num++; } } }
我们可以写一个类来简单测试一下:
import java.io.file; import java.util.linkedlist; public class filesystem { public static int num; public static void main(string[] args) { long a = system.currenttimemillis(); //string path="c:"; num=0; string[] lists={"c:","d:"}; /* for(int i=0;i<lists.length;i++){ file file=new file(lists[i]); scandirrecursion(file); */ for(int i=0;i<lists.length;i++){ scandirnorecursion(lists[i]); } system.out.print("文件总数:"+num); system.out.print("总耗时:"); system.out.println(system.currenttimemillis() - a); }
测试结果:
递归:
文件总数:189497 总耗时:39328
非递归:
文件总数:189432 总耗时:37469
这里非递归相对要好~