package file; import java.io.*; public class FileReader { public static void main(String[] args){ // Demo1(); // Demo2(); // Demo3(); // Demo4(); // Demo5(); //Demo6(); Demo7(); } //file的使用例子 public static void Demo1() { File f = new File("e:\\file"); if(f.isDirectory()) { System.out.println(f.getPath()); } } public static void Demo2() { File f; //File.separator是分隔符,由於不一樣平臺可能用的不同,windows可能用\\而linux可能用// f = new File("e:" + File.separator + "file" + File.separator + "io.txt");//得到路徑句柄 try { System.out.println(f.createNewFile());//建立文件 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //f.delete(); System.out.println(f.getPath()); } public static void Demo3() { File f=new File("e:\\file\\demo.txt");//構造一個路徑的句柄 System.out.println(f.getPath()); System.out.println(f.getParent()); if(f.exists())//若是文件存在則刪除,不存在則生成 { f.delete(); //System.out.println("文件已經存在!"); } else { try { System.out.println(f.createNewFile()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void Demo4() { File file=new File("e:"+File.separator+"file");//得到e:file文件句柄 String[] str=file.list();//使用list()將裏面的文件都放在String 數組裏 for(int i=0;i<str.length;i++) { System.out.println(str[i]); } } public static void fun(File f){ //判斷給定的路徑是不是目錄,若是是目錄在列出 if(f.isDirectory()){ File[] file = f.listFiles(); //再依次循環進行判斷 try{ for(int i = 0;i < file.length;i++){ //繼續把內容傳入到fun方法之中進行驗證 fun(file[i]); } }catch(Exception e){} } else{ System.out.println(f); } } //使用遞歸調用 掃描e盤全部的文件 public static void Demo5() { File file=new File("e:\\"); fun(file); } //fileInputStream的使用例子 public static void Demo6()//錯誤例子,不能直接用String將字節流轉爲字符,應該用InputStreamReader { try { File file=new File("e:"+File.separator+"file"+File.separator+"io.txt"); FileInputStream fis=new FileInputStream(file); byte[] b=new byte[fis.available()]; fis.read(b);//將文件的內容讀取到byte數組中 fis.close(); String str=new String(b);//怎麼會亂碼??? System.out.println(str); } catch(IOException e) { e.printStackTrace(); } } public static void Demo7() { try { String encoding="GBK"; File file=new File("e:"+File.separator+"file"+File.separator+"io.txt"); FileInputStream fis=new FileInputStream(file);//從句柄中讀取文件的字節流,建立字節流對象 if(file.isFile() && file.exists()) { InputStreamReader isr=new InputStreamReader(fis,encoding);//將字節流轉化爲字符流,建立字符流對象 BufferedReader bfr=new BufferedReader(isr);//BufferedReader對使用者輸入的字符進行緩衝 String line=null; while((line=bfr.readLine())!=null) { System.out.println(line); } bfr.close(); } } catch(IOException e) { e.printStackTrace(); } } }