Java 文件写操作
在进行文件写操作的时候,有两种操作方方式。一个是连续写,一个是覆盖式写。
代码如下:
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
// text:要写入的内容;isAppend:写入方式,true为连续写,false为覆盖式写入。
public void write(String text, boolean isAppend) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("D:/file.txt", isAppend)));
bw.write(text);
bw.flush();
bw.close();
}
// FileOutputStream源码如下
public FileOutputStream(String name, boolean append)
throws FileNotFoundException {
this(name != null ? new File(name) : null, append);
}
public FileOutputStream(File file, boolean append)
throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(name);
}
if (name == null) {
throw new NullPointerException();
}
fd = new FileDescriptor();
fd.incrementAndGetUseCount();
this.append = append;
if (append) {
openAppend(name);
} else {
open(name);
}
}
/**
* Opens a file, with the specified name, for appending.
* @param name name of file to be opened
*/
private native void openAppend(String name) throws FileNotFoundException;
/**
* Opens a file, with the specified name, for writing.
* @param name name of file to be opened
*/
private native void open(String name) throws FileNotFoundException;
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。