Java文件操作之按行读取文件和遍历目录的方法
按行读取文件
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
这里非递归相对要好~
赞 (0)