您的位置:首页 > 编程语言 > Java开发

Java进阶(二十二)使用FileOutputStream写入文件

2016-01-12 12:02 615 查看

Java使用FileOutputStream写入文件

在Java中,文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。请参阅下面的完整的例子。

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例如,使用新的“尝试资源关闭”的方法来轻松处理文件。

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


参考文献

http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html

美文美图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: