手机
当前位置:查字典教程网 >编程开发 >Java >java文件输出流写文件的几种方法
java文件输出流写文件的几种方法
摘要:java文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。复制代码代码如下:pa...

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 获取指定日期的实现方法总结

java 学习笔记(入门篇)_程序流程控制结构和方法

java map遍历的四种方法总结

Java线程关闭的3种方法

深入java事件注册的应用分析

Java代码重构的几种模式详解

java中关于Map的三种遍历方法详解

精品推荐
分类导航