簡單介紹幾種檔案的操作
工具/原料
win7
MyEclipse
jdk1.6
方法/步驟
1.檔案的寫入
public static void main(String[] args) {
try {
// 建立檔案outfilename,並寫入內容
BufferedWriter out = new BufferedWriter(new FileWriter(
"outfilename"));
out.write("天氣晴朗!生活很美好!");
out.close();
}
} catch (IOException e) {
}
}
結果見下圖:
2.檔案的讀取
程式碼銜接上文
// 讀檔案outfilename
BufferedReader in = new BufferedReader(
new FileReader("outfilename"));
String str;
while ((str = in.readLine()) != null) {
System.out.println("讀取內容為:"+str);
}
結果見下圖:
3.檔案的內容複製到另一個檔案
程式碼銜接上文
// 複製檔案到另一個檔案
InputStream ins = new FileInputStream(new File("outfilename"));
OutputStream outs = new FileOutputStream(new File("outfilename2"));
byte[] buf = new byte[1024];
int len;
while ((len = ins.read(buf)) > 0) {
outs.write(buf, 0, len);
}
ins.close();
outs.close();
BufferedReader in1 = new BufferedReader(new FileReader("outfilename2"));
String strs;
while ((strs = in1.readLine()) != null) {
System.out.println("複製後的檔案讀取內容:" + strs);
}
ins.close();
結果見下圖:
4.向檔案中新增內容
銜接上文程式碼:
// 向檔案中追加內容
out = new BufferedWriter(new FileWriter("outfilename", true));
out.write("活到老學到老!(^=^)");
out.close();
BufferedReader in2 = new BufferedReader(new FileReader("outfilename"));
String str2;
while ((str2 = in2.readLine()) != null) {
System.out.println("追加內容後文件讀取的內容:" + str2);
}
結果見下圖:
5.獲取檔案的長度
銜接上文程式碼:
//得到檔案outfilename的長度
File file = new File("D:/Users/Workspaces/MyEclipse 2014/tests/outfilename");
long size = file.length();
System.out.println("outfilename檔案大小為: " + size);
結果見下圖: