java IO檔案操作
阿新 • • 發佈:2019-01-09
一些範例:
0. 目錄File
遍歷目錄下的檔案
import java.io.File; import java.io.IOException; public class DirErgodic { private static int depth=1; public static void find(String pathName,int depth) throws IOException{ int filecount=0; //獲取pathName的File物件 File dirFile = new File(pathName); //判斷該檔案或目錄是否存在,不存在時在控制檯輸出提醒 if (!dirFile.exists()) { System.out.println("do not exit"); return ; } //判斷如果不是一個目錄,就判斷是不是一個檔案,時檔案則輸出檔案路徑 if (!dirFile.isDirectory()) { if (dirFile.isFile()) { System.out.println(dirFile.getCanonicalFile()); } return ; } for (int j = 0; j < depth; j++) { System.out.print(" "); } System.out.print("|--"); System.out.println(dirFile.getName()); //獲取此目錄下的所有檔名與目錄名 String[] fileList = dirFile.list(); int currentDepth=depth+1; for (int i = 0; i < fileList.length; i++) { //遍歷檔案目錄 String string = fileList[i]; //File("documentName","fileName")是File的另一個構造器 File file = new File(dirFile.getPath(),string); String name = file.getName(); //如果是一個目錄,搜尋深度depth++,輸出目錄名後,進行遞迴 if (file.isDirectory()) { //遞迴 find(file.getCanonicalPath(),currentDepth); }else{ //如果是檔案,則直接輸出檔名 for (int j = 0; j < currentDepth; j++) { System.out.print(" "); } System.out.print("|--"); System.out.println(name); } } } public static void main(String[] args) throws IOException{ find("D:\\MongoDB", depth); } }
1.讀寫
try{ FileInputStream in=new FileInputStream("count.txt"); DataInputStream dataIn=new DataInputStream(in); number=dataIn.readInt(); number++; in.close(); dataIn.close(); } catch(FileNotFoundException e){ [html] view plain copy number++; [html] view plain copy try {FileOutputStream out=new FileOutputStream("count.txt"); DataOutputStream dataOut=new DataOutputStream(out); dataOut.writeInt(number); out.close();dataOut.close(); } catch(IOException ee){} } catch(IOException ee) { } } else{ number++; try{ FileOutputStream out=new FileOutputStream("count.txt"); DataOutputStream dataOut=new DataOutputStream(out); dataOut.writeInt(number); out.close();dataOut.close(); } catch(FileNotFoundException e){} catch(IOException e){} } }
2 按行讀
try{
File f=new File("D:/test","A.txt");
FileReader in=new FileReader(f);
BufferedReader buffer=new BufferedReader(in);
String s=null;
while((s=buffer.readLine())!=null)
{ out.print(s+"<BR>");
}
in.close();buffer.close();
}
catch(IOException ee)
{out.print(" 檔案不存在");}