Java文件操作之按行讀取文件和遍歷目次的辦法。本站提示廣大學習愛好者:(Java文件操作之按行讀取文件和遍歷目次的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是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
這裡非遞歸絕對要好~