java基礎-檔案操作
阿新 • • 發佈:2019-02-20
一
建立多級目錄下的一個檔案
二public class FileDemo3 { public static void main(String[] args) throws IOException{ File file = new File( "a"+File.separator+ "b"+File.separator+ "c"+File.separator+ "d"+File.separator+ "e"+File.separator+ "f"+File.separator+ "g"+File.separator+ "h.txt" ); /* * 建立檔案時,應首先判斷當前檔案所在的 * 目錄是否存在,因為若不存在,會丟擲 * 異常的。 */ /* * File getParentFile() * 獲取當前檔案或目錄所在的父目錄 */ File parent = file.getParentFile(); if(!parent.exists()){ parent.mkdirs(); } if(!file.exists()){ file.createNewFile(); System.out.println("檔案建立完畢"); } } }
使用字元流複製文字檔案
三public class CopyDemo { public static void main(String[] args) throws IOException{ FileInputStream fis = new FileInputStream( "./src/day03/CopyDemo.java"); FileOutputStream fos = new FileOutputStream( "CopyDemo.java"); InputStreamReader isr = new InputStreamReader(fis); OutputStreamWriter osw = new OutputStreamWriter(fos); int d = -1; while((d=isr.read())!=-1){ osw.write(d); } System.out.println("拷貝完畢"); isr.close(); osw.close(); } }
一行一行讀取檔案
* PrintWriter
* 緩衝字元輸出流,帶有自動行重新整理
* 可以以行為單位寫出字串
public class PrintWriterDemo { public static void main(String[] args) throws IOException{ FileOutputStream fos = new FileOutputStream("pw.txt"); OutputStreamWriter osw = new OutputStreamWriter( fos,"UTF-8"); /* * 建立具有自動航重新整理的PrintWriter * 後,每當我們使用println方法寫出 * 字串後,都會自動flush * 但一定要清楚:這無疑會增加寫出次數 * 而降低寫出效率 */ PrintWriter pw = new PrintWriter(osw,true); pw.println("我愛北京天安門"); pw.println("快使用雙節棍"); pw.close(); } }
四
一行一行寫入檔案
* BufferedReader
* 緩衝字元輸入流
* 可以以行為單位讀取字串
public class BufferReaderDemo {
public static void main(String[] args) throws IOException{
FileInputStream fis
= new FileInputStream("pw.txt");
InputStreamReader isr
= new InputStreamReader(
fis,"UTF-8");
BufferedReader br
= new BufferedReader(isr);
/*
* String readLine()
* 一次讀取一行字串,該方法會判斷
* 讀取到換行符為止,將之前的一行
* 字串返回
* 若該方法返回的字串為null,說明
* 沒有資料可讀了。
*/
String str = null;
while((str=br.readLine())!=null){
System.out.println(str);
}
br.close();
}
}