寫文件在開發(fā)小工具時常用到魔招,比如爬取某些網(wǎng)站的信息五辽,數(shù)據(jù)量不是很大杆逗,保存到本地即可。當(dāng)然如果會一些額外的技能蠕蚜,比如多線程悔橄,網(wǎng)絡(luò)之類的腺毫,小工具會更加有意思拴曲。
這里看下Java不同的寫文件方式:
- BufferedWriter
- PrintWriter
- FileOutputStream
- DataOutputStream
- RandomAccessFile
- FileChannel
- Files
BufferedWriter
把類中定義的方法信息凛忿,寫入文件
static String fileName = "/Users/aihe/tmp/writeFileDemo.txt";
static void writeFileWithBufferedWriter() throws IOException {
Method[] methods = WriteFileDemo.class.getDeclaredMethods();
String str = Arrays.toString(methods);
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(str);
writer.close();
}
追加信息到已經(jīng)存在的文件:
static void appendFileWithBufferedWriter() throws IOException {
// FileWriter的第二個參數(shù)代表是否追加
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName,true));
writer.append("追加信息");
writer.close();
}
PrintWriter
PrintWriter可以輸出格式化的信息到文件中店溢。
static void writingFileWithPrintWriter()
throws IOException {
Method[] methods = WriteFileDemo.class.getDeclaredMethods();
String str = Arrays.toString(methods);
// 可以使用FileWriter,BufferedWriter
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.printf("當(dāng)前類的方法信息: %s \n方法的個數(shù):%d \n", str, methods.length);
printWriter.close();
}
FileOutputStream
用來寫入二進制數(shù)據(jù)到文件中床牧,需要將String轉(zhuǎn)換為bytes戈咳。
static void writingFileWithFileOutputStream()
throws IOException {
Method[] methods = WriteFileDemo.class.getDeclaredMethods();
String str = Arrays.toString(methods);
FileOutputStream outputStream = new FileOutputStream(fileName);
// 需要將String轉(zhuǎn)換為bytes
byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
DataOutputStream
寫法如上
static void writingFileWithDataOutputStream()
throws IOException {
Method[] methods = WriteFileDemo.class.getDeclaredMethods();
String str = Arrays.toString(methods);
FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
outStream.writeUTF(str);
outStream.close();
// verify the results
String result;
FileInputStream fis = new FileInputStream(fileName);
DataInputStream reader = new DataInputStream(fis);
result = reader.readUTF();
reader.close();
System.out.println(result.equals(str));
}
RandomAccessFile
想要寫入或者編輯一個已經(jīng)存在的文件著蛙,而不是寫入一個全新的文件或者單純的追加,那么我們可以使用RandomAccessFile猎唁。這個類可以讓我們寫入特定的位置顷蟆,如下:
寫入中文的時候使用writeUTF方法,不然可能會亂碼
static void writeToPositionWithRAF(String filename, long position)
throws IOException {
RandomAccessFile writer = new RandomAccessFile(filename, "rw");
writer.seek(position);
//寫入中文的時候防止亂碼
writer.writeUTF("新內(nèi)容");
writer.close();
}
FileChannel
在處理大文件的時候,F(xiàn)ileChannel會比標(biāo)準(zhǔn)的io更快削樊。
static void writeWithFileChannel() throws IOException {
RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
FileChannel channel = stream.getChannel();
String value = WriteFileDemo.class.getSimpleName();
byte[] strBytes = value.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
buffer.put(strBytes);
buffer.flip();
channel.write(buffer);
stream.close();
channel.close();
}
Files
Files是Java7引入的工具類豁生,通過它,我們可以創(chuàng)建嫉父,移動沛硅,刪除眼刃,復(fù)制文件绕辖。目錄也是一種特殊的文件,對目錄也適用擂红。當(dāng)然也可以用于讀寫文件
static void writeWithFiles()
throws IOException {
String str = "Hello";
Path path = Paths.get(fileName);
byte[] strToBytes = str.getBytes();
Files.write(path, strToBytes);
String read = Files.readAllLines(path).get(0);
System.out.println(str.equals(read));
}
最后
操作文件的時候記得要關(guān)閉文件流仪际,也可以使用java7的try-with-resource語法围小。
BufferedWriter 提供高效的讀寫字符树碱,字符串肯适,數(shù)組。
PrintWriter 寫入格式化文字
FileOutputStream 寫入二進制流
DataOutputStream 寫primary類型
RandomAccessFile 隨機讀寫文件成榜,在指定的位置編輯文件
FileChannel 寫入大文件