您好,欢迎来到暴趣科技网。
搜索
您的当前位置:首页java文件输出流写文件的几种方法

java文件输出流写文件的几种方法

来源:暴趣科技网
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(); } }}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baoquwan.com 版权所有 湘ICP备2024080961号-7

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务