Sử dụng FileOutputStream để thêm nội dung file trong Java
1. Thêm nội dung file sử dụng java FileOutputStream
Nội dung fileWrite5.txt
line content : 1
line content : 2
line content : 3
line content : 4
line content : 5
line content : 6
line content : 7
line content : 8
line content : 9
line content : 10
Tạo class AppendContentFileWIthFileOutputStream.java
package com.loop.io;
import java.io.FileOutputStream;
import java.io.IOException;
public class AppendContentFileWIthFileOutputStream {
/**
*
* Create by Cuder
*/
public static void main(String[] args) throws IOException {
FileOutputStream fout = null;
try {
fout = new FileOutputStream("resource/fileWrite5.txt", true);
for (int i = 0; i < 10; i++) {
fout.write(("line content : " + (i + 1) + "\n").getBytes());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != fout) {
fout.close();
}
}
}
}
Kết quả fileWrite5.txt
line content : 1
line content : 2
line content : 3
line content : 4
line content : 5
line content : 6
line content : 7
line content : 8
line content : 9
line content : 10
line content : 1
line content : 2
line content : 3
line content : 4
line content : 5
line content : 6
line content : 7
line content : 8
line content : 9
line content : 10
2. Thêm nội dung file sử dụng try datasource với JDK7
Nội dung fileWrite6.txt
line content : 1
line content : 2
line content : 3
line content : 4
line content : 5
line content : 6
line content : 7
line content : 8
line content : 9
line content : 10
Tạo class AppendContentFileWIthFileOutputStreamTryWithResource.java
package com.loop.io;
import java.io.FileOutputStream;
import java.io.IOException;
public class AppendContentFileWIthFileOutputStreamTryWithResource {
/**
*
* Create by Cuder
*/
public static void main(String[] args) throws IOException {
try (FileOutputStream fout = new FileOutputStream(
"resource/fileWrite6.txt", true)) {
for (int i = 0; i < 10; i++) {
fout.write(("line content : " + (i + 1) + "\n").getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Kết quả fileWrite6.txt
line content : 1
line content : 2
line content : 3
line content : 4
line content : 5
line content : 6
line content : 7
line content : 8
line content : 9
line content : 10
line content : 1
line content : 2
line content : 3
line content : 4
line content : 5
line content : 6
line content : 7
line content : 8
line content : 9
line content : 10