java写入文件的几种方法分享
作者:shangke 发布时间:2023-06-26 15:56:55
一,FileWritter写入文件
FileWritter, 字符流写入字符到文件。默认情况下,它会使用新的内容取代所有现有的内容,然而,当指定一个true (布尔)值作为FileWritter构造函数的第二个参数,它会保留现有的内容,并追加新内容在文件的末尾。
1. 替换所有现有的内容与新的内容。
new FileWriter(file);2. 保留现有的内容和附加在该文件的末尾的新内容。
new FileWriter(file,true);
追加文件示例
一个文本文件,命名为“javaio-appendfile.txt”,并包含以下内容。
ABC Hello追加新内容 new FileWriter(file,true)
package com.yiibai.file;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class AppendToFileExample
{
public static void main( String[] args )
{
try{
String data = " This content will append to the end of the file";
File file =new File("javaio-appendfile.txt");
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
}
}
结果
现在,文本文件“javaio-appendfile.txt”内容更新如下:
ABC Hello This content will append to the end of the file
二,BufferedWriter写入文件
缓冲字符(BufferedWriter )是一个字符流类来处理字符数据。不同于字节流(数据转换成字节),你可以直接写字符串,数组或字符数据保存到文件。
package com.yiibai.iofile;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("/users/mkyong/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
三,FileOutputStream写入文件
文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。请参阅下面的完整的例子。
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.io的几种读写文件的方式
一、java把这些不同来源和目标的数据都统一抽象为数据流。
Java语言的输入输出功能是十分强大而灵活的。
在Java类库中,IO部分的内容是很庞大的,因为它涉及的领域很广泛:标准输入输出,文件的操作,网络上的数据流,字符串流,对象流,zip文件流等等。
这里介绍几种读写文件的方式
二、InputStream、OutputStream(字节流)
//读取文件(字节流)
FileInputStream in = new FileInputStream("d:\\1.txt");
//写入相应的文件
FileOutputStream out = new FileOutputStream("d:\\2.txt");
//读取数据
//一次性取多少字节
byte[] bytes = new byte[2048];
//接受读取的内容(n就代表的相关数据,只不过是数字的形式)
int n = -1;
//循环取出数据
while ((n = in.read(bytes,0,bytes.length)) != -1) {
//转换成字符串
String str = new String(bytes,0,n,"UTF-8"); #这里可以实现字节到字符串的转换,比较实用
System.out.println(str);
//写入相关文件
out.write(bytes, 0, n);
//清除缓存向文件写入数据
out.flush();
}
//关闭流
in.close();
out.close();
三、BufferedInputStream、BufferedOutputStream(缓存字节流)使用方式和字节流差不多,但是效率更高(推荐使用)
//读取文件(缓存字节流)
BufferedInputStream in=new BufferedInputStream(new FileInputStream("d:\\1.txt"));
//写入相应的文件
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream("d:\\2.txt"));
//读取数据
//一次性取多少字节
byte[] bytes = new byte[2048];
//接受读取的内容(n就代表的相关数据,只不过是数字的形式)
int n = -1;
//循环取出数据
while ((n = in.read(bytes,0,bytes.length)) != -1) {
//转换成字符串
String str = new String(bytes,0,n,"UTF-8");
System.out.println(str);
//写入相关文件
out.write(bytes, 0, n);
//清除缓存,向文件写入数据
out.flush();
}
//关闭流
in.close();
out.close();
四、InputStreamReader、OutputStreamWriter(字节流,这种方式不建议使用,不能直接字节长度读写)。使用范围用做字符转换
//读取文件(字节流)
InputStreamReader in = new InputStreamReader(new FileInputStream("d:\\1.txt"),"UTF-8");
//写入相应的文件
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("d:\\2.txt"));
//读取数据
//循环取出数据
char[] chars = new char[2048];
int len = -1;
while ((len = in.read(chars,0,chars.length)) != -1) {
System.out.println(len);
//写入相关文件
out.write(chars,0,len);
//清除缓存
out.flush();
}
//关闭流
in.close();
out.close();
五、BufferedReader、BufferedWriter(缓存流,提供readLine方法读取一行文本)
FileInputStream fileInputStream = new FileInputStream("d:\\1.txt");
FileOutputStream fileOutputStream = new FileOutputStream("d:\\2.txt", true);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"UTF-8");
//读取文件(字符流)
BufferedReader in = new BufferedReader(inputStreamReader,"UTF-8"));#这里主要是涉及中文
//BufferedReader in = new BufferedReader(new FileReader("d:\\1.txt")));
//写入相应的文件
BufferedWriter out = new BufferedWriter(outputStreamWriter,"UTF-8"));
//BufferedWriter out = new BufferedWriter(new FileWriter("d:\\2.txt"));
//读取数据
//循环取出数据
String str = null;
while ((str = in.readLine()) != null) {
System.out.println(str);
//写入相关文件
out.write(str);
out.newLine();
//清除缓存向文件写入数据
out.flush();
}
//关闭流
in.close();
out.close();
六、Reader、PrintWriter(PrintWriter这个很好用,在写数据的同事可以格式化)
//读取文件(字节流)
Reader in = new InputStreamReader(new FileInputStream("d:\\1.txt"),"UTF-8");
//写入相应的文件
PrintWriter out = new PrintWriter(new FileWriter("d:\\2.txt"));
//读取数据
//循环取出数据
byte[] bytes = new byte[1024];
int len = -1;
while ((len = in.read()) != -1) {
System.out.println(len);
//写入相关文件
out.write(len);
//清除缓存
out.flush();
}
//关闭流
in.close();
out.close();
七、基本的几种用法就这么多,当然每一个读写的使用都是可以分开的。为了更好的来使用io。流里面的读写,建议使用BufferedInputStream、BufferedOutputStream
猜你喜欢
- 简介对于一个APP来说,肯定会有一个AppBar,这个AppBar一般包含了APP的导航信息等。虽然我们可以用一个固定的组件来做为AppBa
- 前言我们在学习Windows应用程序开发中,经常会用到消息对话框给用户或者管理员一些的消息提示,它们都是基于对MessageBox类的消息对
- 相比于直线检测,直线拟合的最大特点是将所有数据只拟合出一条直线void fitLine( InputArray points, Output
- 最近要给一个 Winform 项目添加功能,需要一个能显示进度条的弹窗,还要求能够中止任务,所以就做了一个,在此做个记录总结。虽然用的是比较
- [LeetCode] 9. Palindrome Number 验证回文数字Determine whether an integer is
- 样例代码在讲 Flutter 的盒子模型前,先看看HTML 中的盒子模型。如下图所示,一个页面元素包括了与父级容器的外边距(margin),
- 问题:在用Java程序进行读写含中文的txt文件时,经常会出现读出或写入的内容会出现乱码。原因其实很简单,就是系统的编码和程序的编码采用了不
- 简介官方API文档Scaffold的of方法说明有说明调用Scaffold.of方法是在Scallfold的子组件的Build方法中,也就是
- 需求: 给定一个URL地址, 例如: http://www.cncounter.com/tools/shorturl.php, 解析对应的I
- 前言RefreshIndicator是Flutter里常见的下拉刷新组件,使用是比较方便的。但由于产品兄弟对其固定的刷新样式很是不满,而且代
- 目录Android 集成Flutter1, Hello Flutter2, 引入 Flutter 模块3,使用Flutter3.1 添加依赖
- yaml语法注解配置文件两种形式application.properties和.yaml第一种语法 key=value第二种key:空格va
- 您已经看到很多包含视频内容的应用程序,比如带有视频教程的食谱应用程序、电影应用程序和体育相关的应用程序。您是否想知道如何将视频内容添加到您的
- 本文实例讲解了iOS从背景图中取色的代码,分享给大家供大家参考,具体内容如下实现代码:void *bitmapData; //内存空间的指针
- 前言这里主要简单介绍如何使用Camera+SurfaceView自定义相机拍照,如果是Camera2或者是TextureView的可以前往主
- 在实际开发中,我们经常会需要在页面跳转的时候携带路由参数,典型的例子就是从列表到详情页的时候,需要携带详情的 id,以便详情页获取对应的数据
- 1、右值1.1 简介首先区分一下左右值:左值是指存储在内存中、有明确存储地址(可取地址)的数据;右值是指可以提供数据值的数据(不可取地址)如
- 一直使用Eclipse环境开发Android,也尝鲜使用过Android Studio去开发,各种IDE配合Android SDK及SDK原
- 本文实例讲述了C#中HttpWebRequest的用法。分享给大家供大家参考。具体如下:HttpWebRequest类主要利用HTTP 协议
- 需求基于MTK8163 8.1平台定制导航栏部分,在左边增加音量减,右边增加音量加思路需求开始做之前,一定要研读SystemUI Navig