File ReadWrite 使用 FileInputStreamFileOutputStream
寫入檔案 test.txt:
String filepath ="C:\\test.txt";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filepath);
byte[] buffer = "This will be written in test.txt".getBytes();
fos.write(buffer, 0, buffer.length);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fos != null)
fos.close();
}
從檔案 test.txt 中讀取:
String filepath ="C:\\test.txt";
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
int length = (int) new File(filepath).length();
byte[] buffer = new byte[length];
fis.read(buffer, 0, length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fis != null)
fis.close();
}
請注意,自 Java 1.7 引入了 try-with-resources 語句之後,使得讀/寫操作的實現變得更加簡單:
寫入檔案 test.txt:
String filepath ="C:\\test.txt";
try (FileOutputStream fos = new FileOutputStream(filepath)){
byte[] buffer = "This will be written in test.txt".getBytes();
fos.write(buffer, 0, buffer.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
從檔案 test.txt 中讀取:
String filepath ="C:\\test.txt";
try (FileInputStream fis = new FileInputStream(filepath)){
int length = (int) new File(filepath).length();
byte[] buffer = new byte[length];
fis.read(buffer, 0, length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}