Java FileWriter (Java FileWriter)

  • Java FileWriter class is a part of java.io package.Java FileWriter类是java.io软件包的一部分。
  • FileWriter is a sub class of java.io.OutputStreamWriter class.FileWriter是java.io.OutputStreamWriter类的子类。
  • FileWriter is meant for writing streams of characters.FileWriter用于编写字符流。
  • FileWriter is used to write to character files. Its write() methods allow you to write character(s) or strings to a file.FileWriter用于写入字符文件。 它的write()方法允许您将字符或字符串写入文件。
  • FileWriters are usually wrapped by higher-level Writer objects, such as BufferedWriter or PrintWriter, which provide better performance and higher-level, more flexible methods to write data.FileWriter通常由更高级别的Writer对象包装,例如BufferedWriter或PrintWriter ,它们提供更好的性能以及更高级别,更灵活的数据写入方法。

FileWriter构造函数 (FileWriter Constructors)

  1. FileWriter(File file): Creates a FileWriter object using specified File object. It throws an IOException if the file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.FileWriter(File file) :使用指定的File对象创建一个FileWriter对象。 如果文件存在但它是目录而不是常规文件,或者不存在但无法创建,或者由于任何其他原因而无法打开,则抛出IOException
  2. FileWriter(File file, boolean append): Creates a FileWriter object using specified File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. It throws an IOException if the file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.FileWriter(File file, boolean append) :使用指定的File对象创建一个FileWriter对象。 如果第二个参数为true,则字节将被写入文件的末尾而不是开头。 如果文件存在但它是目录而不是常规文件,或者不存在但无法创建,或者由于任何其他原因而无法打开,则抛出IOException
  3. FileWriter(FileDescriptor fd): Creates a FileWriter object associated with specified file descriptor.FileWriter(FileDescriptor fd) :创建一个与指定文件描述符关联的FileWriter对象。
  4. FileWriter(String fileName): Creates a FileWriter object using specified fileName. It throws an IOException if the named file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.FileWriter(String fileName) :使用指定的fileName创建一个FileWriter对象。 如果命名文件存在但是目录而不是常规文件,或者不存在但无法创建,或者由于任何其他原因而无法打开,则抛出IOException
  5. FileWriter(String fileName, boolean append): Creates a FileWriter object using specified fileName with a boolean indicating whether or not to append the data written. If the second argument is true, then the data will be written to the end of the file rather than the beginning. It throws an IOException if the named file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.FileWriter(String fileName, boolean append) :使用指定的fileName和一个布尔值创建FileWriter对象,该布尔值指示是否要附加写入的数据。 如果第二个参数为true,则数据将被写入文件的末尾而不是开头。 如果命名文件存在但是目录而不是常规文件,或者不存在但无法创建,或者由于任何其他原因而无法打开,则抛出IOException。

Java FileWriter示例 (Java FileWriter Example)

FileWriter inherits the method of java.io.OutputStreamWriter and java.io.Writer classes.

FileWriter继承了java.io.OutputStreamWriterjava.io.Writer类的java.io.Writer

Let’s have a look at the below methods with examples.

让我们用示例来看看下面的方法。

写(int c) (write(int c))

This method writes a single character specified by int c.

此方法写入一个由int c指定的字符。

package com.journaldev.io.filewriter;import java.io.FileWriter;
import java.io.IOException;/*** Java write file using FileWriter write method* * @author pankaj**/
public class FileWriterWriteIntExample {public static void main(String[] args) {FileWriter fileWriter = null;try {fileWriter = new FileWriter("D:/data/file.txt");//inherited method from java.io.OutputStreamWriter fileWriter.write(65);fileWriter.write(66);fileWriter.write(67);} catch (Exception e) {e.printStackTrace();}finally {try {if (fileWriter != null) {fileWriter.flush();fileWriter.close();                  }} catch (IOException e) {e.printStackTrace();}}}
}

FileWriter implements AutoCloseable interface, hence we can use try with resources while using FileWriter class.

FileWriter实现了AutoCloseable接口,因此在使用FileWriter类时我们可以尝试使用资源 。

package com.journaldev.io.filewriter;import java.io.FileWriter;/*** Java write file using FileWriter write method using try with resource* * @author pankaj**/
public class FileWriterWriteIntTryWithResource {public static void main(String[] args) {try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) {//inherited method from java.io.OutputStreamWriter fileWriter.write(65);fileWriter.write(66);fileWriter.write(67);} catch (Exception e) {e.printStackTrace();}}
}

Note: In the above program fileWriter.write(65) will write A into file because the 65 is the decimal value for the character A, hence integer 65 will be converted into character A and same for the other.

注意 :在上面的程序中,因为65是字符A的十进制值,所以fileWriter.write(65)会将A写入文件,因此整数65将被转换为字符A,其他字符也将转换为字符A。

write(String str,int off,int len) (write(String str, int off, int len))

This method writes a portion of String str from int off to int len.

此方法将String str的一部分从int off写入int len

  • str: String to be writtenstr:要写入的字符串
  • off: Offset from which to start reading charactersoff:开始读取字符的偏移量
  • len: Number of characters to be writtenlen:要写入的字符数

If the value of the len parameter is negative then no characters are written.

如果len参数的值为负,则不会写入任何字符。

package com.journaldev.io.filewriter;import java.io.FileWriter;/*** Java write file using FileWriter write(String  s,  int  off,  int  len) method* * @author pankaj**/
public class FileWriterWriteStringExample {public static void main(String[] args) {String data = "This is FileWriter Example.";try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) {//inherited method from java.io.OutputStreamWriter fileWriter.write(data, 8, 10);} catch (Exception e) {e.printStackTrace();}}
}

写(char [] cbuf,int off,int len) (write(char[] cbuf, int off, int len))

This method writes a portion of an array of characters specified by char[] cbuf from int off to int len.

此方法将char[] cbuf指定的char[] cbuf数组的一部分从int off写入int len

  • cbuf: A character arraycbuf:字符数组
  • off: Offset from which to start reading charactersoff:开始读取字符的偏移量
  • len : Number of characters to writelen:要写入的字符数
package com.journaldev.io.filewriter;import java.io.FileWriter;/*** Java write file using FileWriter write(char[] cbuf,  int  off,  int  len) method* * @author pankaj**/
public class FileWriterWriteCharArray {public static void main(String[] args) {char[] data = "This is FileWriter Example.".toCharArray();try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) {//inherited method from java.io.OutputStreamWriter fileWriter.write(data, 8, 10);} catch (Exception e) {e.printStackTrace();}}
}

写(char [] cbuf) (write(char[] cbuf))

This method writes the array of character specified by cbuf.

此方法写入cbuf指定的字符数组。

package com.journaldev.io.filewriter;import java.io.FileWriter;/*** Java write file using FileWriter write(char[] cbuf) method* * @author pankaj**/
public class FileWriterWriteCharArrayExample {public static void main(String[] args) {char[] data = "This is FileWriter Example.".toCharArray();try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) {//inherited method from java.io.Writer fileWriter.write(data);} catch (Exception e) {e.printStackTrace();}}
}

write(String str) (write(String str))

This method writes a string value into file specified by str.

此方法将字符串值写入str指定的文件中。

package com.journaldev.io.filewriter;import java.io.FileWriter;/*** Java write file using FileWriter write(String  str) method* * @author pankaj**/
public class FileWriterWriteString {public static void main(String[] args) {try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) {//inherited method from java.io.Writer fileWriter.write("JournalDev");} catch (Exception e) {e.printStackTrace();}}
}

追加(字符c) (append(char c))

This method appends the specified character to this writer where c is the 16-bit character to append.

此方法将指定的字符附加到此编写器,其中c是要附加的16位字符。

package com.journaldev.io.filewriter;import java.io.FileWriter;/*** Java write file using FileWriter append(char c) method* * @author pankaj**/
public class FileWriterAppendCharacter {public static void main(String[] args) {try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) {//inherited method from java.io.Writer fileWriter.write("JournalDev");fileWriter.append('C');} catch (Exception e) {e.printStackTrace();}}
}

flush() (flush())

This method flushes the stream. When flush() method is called it immediately writes the data to the output file.

此方法刷新流。 调用flush()方法时,它将立即将数据写入输出文件。

package com.journaldev.io.filewriter;import java.io.FileWriter;/*** Java write file with FileWriter flush() method* * @author pankaj**/
public class FileWriterFlushExample {public static void main(String[] args) {try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) {//inherited method from java.io.Writer fileWriter.write("JournalDev");//inherited method from java.io.OutputStreamWriterfileWriter.flush();fileWriter.write(" Tutorials");fileWriter.flush();} catch (Exception e) {e.printStackTrace();}}
}

关() (close())

This method flush the stream before close it. Once the stream has been closed, invocation of write() or flush() method will cause an IOException to be thrown. Closing a previously closed stream has no effect.

此方法在关闭流之前先对其进行冲洗。 一旦关闭流,调用write()flush()方法将导致引发IOException 。 关闭先前关闭的流无效。

package com.journaldev.io.filewriter;import java.io.FileWriter;/*** Java write file with FileWriter close() method* * @author pankaj**/
public class FileWriterCloseExample {public static void main(String[] args) {try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) {//inherited method from java.io.Writer fileWriter.write("JournalDev");//inherited method from java.io.OutputStreamWriterfileWriter.close();;fileWriter.write(" Tutorials");} catch (Exception e) {e.printStackTrace();}}
}

Output:

输出:

java.io.IOException: Stream closedat sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)at sun.nio.cs.StreamEncoder.write(Unknown Source)at sun.nio.cs.StreamEncoder.write(Unknown Source)at java.io.OutputStreamWriter.write(Unknown Source)at java.io.Writer.write(Unknown Source)at com.journaldev.examples.FileWriterCloseExample.main(FileWriterCloseExample.java:20)

FileWriter与FileOutputStream (FileWriter vs FileOutputStream)

  • FileWriter is meant for writing streams of characters while FileOutputStream is used for writing streams of raw bytes.FileWriter用于写入字符流,而FileOutputStream用于写入原始字节流。
  • FileWriter deal with 16-bit characters while FileOutputStream deals with 8-bit bytes.FileWriter处理16位字符,而FileOutputStream处理8位字节。
  • FileWriter can handle Unicode strings while FileOutputStream writes bytes to a file and do not accepts characters or strings hence it needs to wrapped up by OutputStreamWriter to accept strings.FileWriter可以处理Unicode字符串,而FileOutputStream将字节写入文件中并且不接受字符或字符串,因此需要由OutputStreamWriter对其进行包装以接受字符串。

Also check java write file for more about how to write file in java.

另请检查Java写入文件以获取有关如何在Java中写入文件的更多信息。

That’s all for Java FileWriter, I hope nothing important got missed here.

Java FileWriter就这些了,我希望这里没有重要的事情。

GitHub Repository.GitHub Repository下载所有示例代码。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/20891/java-filewriter-example

Java FileWriter示例相关推荐

  1. java filewriter 编码_Java FileWriter 类

    Java FileWriter 类 在本教程中,我们将借助示例学习Java FileWriter及其方法. java.io包的FileWriter类可用于将数据(以字符为单位)写入文件. 它继承了Ou ...

  2. 大数据 java 代码示例_功能Java示例 第7部分–将失败也视为数据

    大数据 java 代码示例 这是称为" Functional Java by Example"的系列文章的第7部分. 我在本系列的每个部分中开发的示例是某种"提要处理程序 ...

  3. java方法示例注释 @_Java 8中的功能接口是什么? @功能注释和示例

    java方法示例注释 @ 函数接口是Java 8最重要的概念之一,实际上为lambda表达式提供了动力,但是许多开发人员没有首先了解函数接口在Java 8中的作用就花了很多精力来理解它,并花时间学习l ...

  4. java 方法 示例_Java 9示例–收集的工厂方法–创建不可修改的列表,集合和映射...

    java 方法 示例 大家好,这是我在该博客上发表的有关Java 9功能的第一篇文章,今天您将了解我最喜欢的功能"收集的工厂方法" ,它是JEP 269的一部分.JEP代表JDK增 ...

  5. java 观察者模式示例_观察者设计模式示例

    java 观察者模式示例 本文是我们名为" Java设计模式 "的学院课程的一部分. 在本课程中,您将深入研究大量的设计模式,并了解如何在Java中实现和利用它们. 您将了解模式如 ...

  6. java 泛型示例_使用Java泛型的模板方法模式示例

    java 泛型示例 如果您发现除了某些部分外,您的许多例程完全相同,那么您可能需要考虑使用Template Method来消除容易出错的代码重复 . 这是一个示例:下面是两个做类似事情的类: 实例化并 ...

  7. java 设计模式 示例_Java中的状态设计模式–示例教程

    java 设计模式 示例 状态模式是行为设计模式之一 . 当对象根据其内部状态更改其行为时,将使用状态设计模式. 如果必须根据对象的状态更改其行为,则可以在对象中使用状态变量,并使用if-else条件 ...

  8. java 设计模式 示例_Java中的访问者设计模式–示例教程

    java 设计模式 示例 访客模式是行为设计模式之一 . 当我们必须对一组相似类型的对象执行操作时,将使用访问者模式. 借助访问者模式,我们可以将操作逻辑从对象移动到另一个类. 例如,假设有一个购物车 ...

  9. java 观察者模式示例_Java中的观察者设计模式-示例教程

    java 观察者模式示例 观察者模式是行为设计模式之一 . 当您对对象的状态感兴趣并希望在发生任何更改时得到通知时,观察者设计模式很有用. 在观察者模式中,监视另一个对象状态的对象称为Observer ...

最新文章

  1. 2021年传感器行业的机遇与风险 | 深度思考
  2. rtti是什么java_RTTI
  3. android布局中显示隐藏动画
  4. JavaScript实现Floyd-Warshall算法(附完整源码)
  5. ArcGIS for Android示例解析之离线地图-----LocalTiledLayer
  6. 圆平移后的方程变化_平移法解题
  7. 浅谈FFT(快速博立叶变换)学习笔记
  8. java为什么删除jpg删不掉_java-如何在不损失质量的情况下从图像(JPG)删除元数据?...
  9. 使用c#访问access数据库
  10. LEDE独臂路由器无法上网踩坑
  11. 安装SQL server需要重启计算机,解决安装sql server 需要重启问题
  12. 如何获得大学教材的PDF版本?
  13. 英特尔oneAPI—开发生物序列聚类工具
  14. 新计算机分区,新电脑如何分区 新电脑怎么分盘
  15. 一个low逼的boofuzz脚本生成器
  16. JavaWeb技术内幕二:Java IO工作机制
  17. Arduino 控制RFID读写器读写 IC卡
  18. 【目标跟踪】|STARK
  19. 那些与三维激光扫描有关的建模
  20. 怎么用python画花瓣_使用Python画一朵美丽的玫瑰花

热门文章

  1. java中的异常和处理
  2. jquery一些 事件的用法
  3. Delphi【变体记录及存储方式】
  4. [转载] Python中的numpy linalg模块
  5. [转载] 快速入门(完整):Python实例100个(基于最新Python3.7版本)
  6. ubuntu环境下,ubuntu16.04装机到nvdia显卡驱动安装、cuda8安装、cudnn安装
  7. 浅析 JNDI / DataSource / ConnectionPool 三者
  8. js中去掉字符串中的某个指定字符
  9. Android 一个页面上下两个ListView的页面显示
  10. 关于Jquery.Data()和HTML标签的data-*属性