首页 > 编程语言 >盘点java写入文件的几种方法

盘点java写入文件的几种方法

时间:2023-12-19 19:15:23浏览次数:32  
标签:文件 java 写入 盘点 file new txt out

盘点java写入文件的几种方法

这篇文章主要介绍了java写入文件的几种方法,需要的朋友可以参考下

一,FileWritter写入文件

FileWritter, 字符流写入字符到文件。默认情况下,它会使用新的内容取代所有现有的内容,然而,当指定一个true (布尔)值作为FileWritter构造函数的第二个参数,它会保留现有的内容,并追加新内容在文件的末尾。

1. 替换所有现有的内容与新的内容。

new FileWriter(file);2. 保留现有的内容和附加在该文件的末尾的新内容。

new FileWriter(file,true);

追加文件示例
一个文本文件,命名为“javaio-appendfile.txt”,并包含以下内容。

ABC Hello追加新内容 new FileWriter(file,true)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

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 )是一个字符流类来处理字符数据。不同于字节流(数据转换成字节),你可以直接写字符串,数组或字符数据保存到文件。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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写入文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

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(字节流)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

//读取文件(字节流)

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(缓存字节流)使用方式和字节流差不多,但是效率更高(推荐使用)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

//读取文件(缓存字节流)

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(字节流,这种方式不建议使用,不能直接字节长度读写)。使用范围用做字符转换

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

//读取文件(字节流)

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方法读取一行文本)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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这个很好用,在写数据的同事可以格式化)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

//读取文件(字节流)

    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

转自:微点阅读   https://www.weidianyuedu.com

原文链接:https://blog.csdn.net/xinyuerr/article/details/132870698

标签:文件,java,写入,盘点,file,new,txt,out
From: https://www.cnblogs.com/sunny3158/p/17914473.html

相关文章

  • 无涯教程-Java - 处理线程死锁函数
    死锁描述了一种情况,其中两个或多个线程永远被阻塞,互相等待,当多个线程需要相同的锁但以不同的顺序获得它们时,就会发生死锁。Java多线程程序可能会遇到死锁情况,因为synchronized关键字会导致正在执行的线程在等待与指定对象关联的锁时被阻塞。这是一个示例。publicclassTestT......
  • 秦疆的Java课程笔记:78 异常 捕获和抛出异常
    异常处理五个关键词:try,catch,finally,throw,throws写一个会出错的代码:publicclassTest1{publicstaticvoidmain(String[]args){inta=1;intb=0;System.out.println(a/b);}}====运行报错====Exceptionint......
  • JavaWeb - Day10 - 案例 - 部门管理、员工管理
    01.案例-准备工作需求&环境搭建1、部门管理部门管理功能开发包括:查询部门列表删除部门新增部门修改部门2、员工管理员工管理功能开发包括:查询员工列表(分页、条件)删除员工新增员工修改员工环境搭建步骤:准备数据库表(dept、emp)创建......
  • 一些有趣和实用的Java开发技巧和编码技巧
    当涉及到Java开发技巧和编码技巧时,有一些有趣和实用的技巧可以帮你提高效率和代码质量。以下是一些示例:1.使用Lambda表达式List<Integer>numbers=Arrays.asList(1,2,3,4,5);//使用Lambda表达式计算偶数的总和intsum=numbers.stream().(n->n%20......
  • Java Properties配置文件使用方法入门详解​
    JavaProperties配置文件使用方法详解使用配置文件的优点:好处1:可以把软件的设置永久化存储好处2:如果我们要修改参数,不需要改动代码,直接修改配置文件就可以了Properties配置文件文件后缀名为.properties,其内容是按键值对存储的。前面为键,后面为值。properties是一个双列集合,拥有Ma......
  • java,类、实例化、构造方法、this关键字、方法重载
    编写类的步骤:1、定义类名2、编写类的属性3、编写类的方法public 访问修饰符,表示在整个项目中都可以调用,也可以用其他词使用class关键字来定义类,如下,定义一个Cat类给了属性和方法,动态方法是没有static的publicclassCat{//属性Stringni_chen;Stringco......
  • jQuery与JavaScript与ajax三者的区别与联系
    简单总结:1、JS是一门前端语言。2、Ajax是一门技术,它提供了异步更新的机制,使用客户端与服务器间交换数据而非整个页面文档,实现页面的局部更新。3、jQuery是一个框架,它对JS进行了封装,使其更方便使用。jQuery使得JS与Ajax的使用更方便 关系比喻:若把js比作木头,那么jquery就是......
  • 秦疆的Java课程笔记:77 异常 Error和Exception
    实际工作中,遇到的情况不可能非常完美。比如:写好的某个模块,用户输入不一定符合要求;程序要打开某个文件,但这个文件可能不存在或者格式不对;你要读取数据库的数据,数据可能是空的;程序在跑着,内存或者硬盘满了……等等情况。软件程序在运行过程中,这类例外情况,通称“异常”,英文:Exception......
  • 无涯教程-Java - Comparator 比较器函数
    TreeSet和TreeMap都按排序顺序存储元素。但是,比较器(Comparator)精确地定义了排序顺序的含义。比较器(Comparator)接口定义了两个方法:compare()和equals()。Compare方法intcompare(Objectobj1,Objectobj2)obj1和obj2是要比较的对象。如果对象相等,则此方法返回零。如果obj......
  • 启动微服务报错:java.lang.IllegalStateException: Service id not legal hostname (se
    Order微服务通过opneFeign调用storage和account时报错原因分析:服务名称不能有下划线,可以使用中划线,Springcloud无法识别下划线,将下划线改为中划线即可注意:这个改了之后,你在进行远程调用的时候,接口对应的方法接口也需要相应改变【分布式开发,一个微服务模块修改了,很可能......