java文件输出流写文件的几种方法
java文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。
package com.yiibai.io;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
public class writefileexample {
public static void main(string[] args) {
fileoutputstream fop = null;
file file;
string content = "this is the text content";
try {
file = new file("c:/newfile.txt");
fop = new fileoutputstream(file);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createnewfile();
}
// get the content in bytes
byte[] contentinbytes = content.getbytes();
fop.write(contentinbytes);
fop.flush();
fop.close();
system.out.println("done");
} catch (ioexception e) {
e.printstacktrace();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (ioexception e) {
e.printstacktrace();
}
}
}
}
//更新的jdk7例如,使用新的“尝试资源关闭”的方法来轻松处理文件。
package com.yiibai.io;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
public class writefileexample {
public static void main(string[] args) {
file file = new file("c:/newfile.txt");
string content = "this is the text content";
try (fileoutputstream fop = new fileoutputstream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createnewfile();
}
// get the content in bytes
byte[] contentinbytes = content.getbytes();
fop.write(contentinbytes);
fop.flush();
fop.close();
system.out.println("done");
} catch (ioexception e) {
e.printstacktrace();
}
}
}
上一篇: 1.快速创建gulp项目