RandomAccessFile同時具備讀寫文件的能力
讀取文件內容
對於讀取整個文件內容的需求,它提供將文件內容讀取到字節數組的方法
private static String readString( Stringpath ) {
try{
File file = new File(path);
RandomAccessFile raf = newRandomAccessFile(file,"rw");
byte[] bytes = newbyte[(int)file.length()];
raf.read(bytes);
raf.close();
String str = new String(bytes);
return str;
}catch (IOException e) {
return "";
}
}
final String path ="C:\\Users\\admin\\Desktop\\text.txt";
String content = readString(path);
System.out.println( content );
注意:如果文件編碼不是utf-8,則會讀到亂碼
寫入文件內容
將內容通過RandomAccessFile寫入文件實現起來比較麻煩, RandomAccessFile提供的寫文件內容方法支持在已有文件內容的某個點插入新內容,而寫文件的大多數需求是用新的內容覆蓋掉舊的內容,RandomAccessFile卻沒有提供清空舊文件內容的方法。 所以要實現此功能我們必須使用FileChannel, FileChannel的truncate方法可以清空文件內容。
private static void writeString( Stringpath, String content) {
try{
byte[] bytes = content.getBytes();
File file = new File(path);
RandomAccessFile raf = newRandomAccessFile(file,"rw");
FileChannel fileChannel =raf.getChannel();
fileChannel.truncate(0);
ByteBuffer byteBuffer =ByteBuffer.wrap(bytes);
fileChannel.write(byteBuffer);
fileChannel.close();
raf.close();
}catch (IOException e) {
}
}
final String path ="C:\\Users\\admin\\Desktop\\text.txt";
writeString(path,"content");
以上代碼的實現步驟是
- 從RandomAccessFile獲得FileChannel
- 調用FileChannel的truncate方法清空文件,truncate接口一個數值參數, 此參數是一個位置值, 表示在文件內容中,此位置後面的內容將被刪除,因此, 傳遞0就表示位置0後面的內容被刪除,也就是整個文件中的內容被刪除
- 利用ByteBuffer往FileChannel中寫入內容
使用標準的方式讀寫文件
使用RandomAccessFile讀寫文件顯得非常繁瑣。 事實,jdk中已經包含了專門實現讀寫文件功能的類庫,如 FileReader 和 FileWriter
FileReader讀取文件內容
private static StringreadStringByReader(String path) {
try {
File file = new File(path);
FileReader fileReader = newFileReader(file);
char[] chars = newchar[(int)file.length()];
fileReader.read(chars);
fileReader.close();
String str = new String(chars);
return str;
} catch (IOException e) {
return "";
}
}
FileWriter寫入文件內容
private static voidwriteStringByWriter(String path , String content ) {
try {
File file = new File(path);
FileWriter fileWriter = newFileWriter(file);
fileWriter.write(content);
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
看, 使用專門的讀寫API實現讀寫文件的功能是不是方便很多, 不但使用方便, 而且可讀性強。