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(); } }}