|
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(); } } }
您可能感兴趣的文章:- Java从控制台读入数据的几种方法总结
- Java文件操作之按行读取文件和遍历目录的方法
- Java简单从文件读取和输出的实例
- Java实现按行读取大文件
- java 按行读取文件并输出到控制台的方法
(编辑:安卓应用网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|