java檔案操作 (1)——判別指定檔案是否存在,讀取檔案修改時間和大小,讀取文字檔案內容,向文字檔案中寫入指定內容
阿新 • • 發佈:2018-12-11
任務要求:
-
完成一個java application應用程式,判別指定路徑下指定檔名的檔案是否存在。
-
如果指定檔案存在,讀取並分別顯示其修改時間和檔案大小等屬性。
-
以文字方式開啟某一指定路徑指定檔名的文字檔案,讀取其內容並顯示。
-
以文字方式向某一指定路徑指定檔名的文字檔案寫入指定文字內容,例如寫入自己的姓名和學號。
1.新建一個文件,名為zhl.txt
程式碼如下:
import java.io.File; import java.io.IOException; class CreateFile { public static void main(String[] args) { try { File file = new File("E:/java task/zhl.txt");//使用 File() 方法來建立一個檔案物件 if(file.createNewFile())//建立一個zhl.txt檔案 System.out.println("檔案建立成功"); else System.out.println("出錯了,該檔案已經存在"); } catch (IOException ioe) { ioe.printStackTrace(); } } }
結果如下:
2.判別指定路徑下指定檔名的檔案是否存在。(例如檔案:E:/java task/zhl.txt)
程式碼如下:
import java.io.File; class DetectFile { public static void main(String[] args) { File file = new File("E:/java task/zhl.txt");//使用 File() 方法來建立一個檔案物件 if(file.exists())//檢測檔案是否存在 { System.out.println("zhl.txt檔案存在"); } else { System.out.println("檔案不存在"); } } }
結果如下:
3.如果指定檔案存在,讀取並分別顯示其修改時間和檔案大小等屬性。
程式碼如下:
import java.io.File; import java.util.Date; public class SizeFile { public static long getFileSize(String filename) { File file = new File(filename);//使用 File() 方法來建立一個檔案物件 if (!file.exists() || !file.isFile()) //判斷檔案是否存在 { System.out.println("檔案不存在"); return -1; } return file.length();//返回檔案大小 } public static void main(String[] args) { long size = getFileSize("E:/java task/zhl.txt");//獲取檔案大小 System.out.println("zhl.txt檔案大小為: " + size);//輸出檔案大小 /*顯示其修改時間*/ File file = new File("E:/java task/zhl.txt"); Long lastModified = file.lastModified(); Date date = new Date(lastModified);//獲取其修改時間 System.out.println("zhl.txt修改時間為:"+date); } }
結果如下:
4.以文字方式開啟某一指定路徑指定檔名的文字檔案,讀取其內容並顯示。(讀取E:/java task/zhl.txt中的內容並顯示)
程式碼如下:
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("E:/java task/zhl.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
System.out.println(str);
} catch (IOException e) {
}
}
}
結果如下:
5.以文字方式向某一指定路徑指定檔名的文字檔案寫入指定文字內容(例如:在E:/java task/zhl.txt中寫入自己的姓名和學號。)
程式碼如下:
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
class WriteFile
{
public static void main(String[] args) throws IOException
{
FileWriter fw = new FileWriter("E:/java task/zhl.txt");//FileWriter 用於寫檔案
BufferedWriter bw = new BufferedWriter(fw);//使用緩衝區的方法將資料寫入到緩衝區中
bw.write("姓名:Grace");//寫入姓名
bw.newLine();//換行
bw.write("學號:20180001");//寫入學號
bw.flush();//使用緩衝區中的方法,將資料重新整理到目的檔案中去
bw.close();//關閉緩衝區,同時關閉了fw流物件
System.out.println("寫入指定文字內容成功");
}
}
結果如下: