遍历相同类型的文件

import java.io.BufferedReader; import java.io.File; import java.io.FilenameFilter; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; public class Test { // 获取给定目录下的同一类型的文件 public static String[] listFile(String path) { File file = new File(path); String[] files = null; if (file.exists()) { files = file.list(new FilenameFilter() { public boolean accept(File dir, String name) { // TODO Auto-generated method stub if (name.endsWith(".java") && new File(dir.getPath() + "//" + name).isFile()) { return true; } else { return false; } } }); } return files; } private static List<String> list = new ArrayList<String>(); // 获取给定的目录或者它的子目录下的同一类型的文件 public static List<String> getFiles(String path) { File file = new File(path); if (file.exists()) { if (file.isFile()) { if (file.getName().endsWith(".java")) { list.add(file.getAbsolutePath()); } } else { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { if (files[i].getName().endsWith(".java")) { list.add(files[i].getAbsolutePath()); } } else { getFiles(files[i].getAbsolutePath()); } } } } return list; } // 根据url获取HTML public static void getHTML(String path) throws Exception { URL url = new URL(path); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); while (reader.ready()) { System.out.println(reader.readLine()); } } public static void main(String[] args) throws Exception { // listFile("D:/test/Test.java"); getFiles("D:/test"); System.out.println(list); String[] files = listFile("D://test"); for (int i = 0; i < files.length; i++) { System.out.println(files[i]); } System.out.println(); getHTML("http://www.roseindia.net/servlets/HistoryOfWebApplication.shtml"); } }

你可能感兴趣的:(exception,String,list,File,url,Path)