|NO.Z.00076|——————————|BigDataEnd|——|Java&IO流.V03|——|Java.v03|IO流.v03|filewriter类|概念使用|

一、FileWriter类(重点)
### --- 基本概念

——>        java.io.FileWriter类主要用于将文本内容写入到文本文件。
二、常用的方法
方法声明 功能介绍
FileWriter(String fileName) 根据参数指定的文件名构造对象
FileWriter
(String fileName, booleanappend)
以追加的方式根据参数指定的文件名来构造对象
void write(int c) 写入单个字符
void write
(char[] cbuf, int off, int len)
将指定字符数组中从偏移量off开始的len个字符写入此文件输出流

void write(char[] cbuf) 将cbuf.length个字符从指定字符数组写入此文件输出流中
void flush()  刷新流
void close()  关闭流对象并释放有关的资源
三、编程代码
package com.yanqi.task17;

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterTest {

    public static void main(String[] args) {
        // 选中代码后可以使用 ctrl+alt+t 来生成异常的捕获代码等
        FileWriter fw = null;

        try {
            // 1.构造FileWrite类型的对象与d:/a.txt文件关联
            // 若文件不存在,该流会自动创建新的空文件
            // 若文件存在,该流会清空文件中的原有内容
            fw = new FileWriter("d:/a.txt");
            // 以追加的方式创建对象去关联文件
            // 若文件不存在则自动创建新的空文件,若文件存在则保留原有数据内容
            //fw = new FileWriter("d:/a.txt", true);
            // 2.通过流对象写入数据内容  每当写入一个字符后则文件中的读写位置向后移动一位
            fw.write('a');

            // 准备一个字符数组
            char[] cArr = new char[]{'h', 'e', 'l', 'l', 'o'};
            // 将字符数组中的一部分内容写入进去
            fw.write(cArr, 1, 3);  // ell
            // 将整个字符数组写进去
            fw.write(cArr); // hello

            // 刷新流
            fw.flush();
            System.out.println("写入数据成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 3.关闭流对象并释放有关的资源
            if (null != fw) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
四、编译打印
D:\JAVA\jdk-11.0.2\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=58839:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath E:\NO.Z.10000——javaproject\NO.H.00001.javase\javase\out\production\javase com.yanqi.task17.FileWriterTest
写入数据成功!

Process finished with exit code 0

 
 
 
 
 
 
 
 
 

Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
                                                                                                                                                   ——W.S.Landor

 

posted on   yanqi_vip  阅读(15)  评论(0编辑  收藏  举报

努力加载评论中...

导航

点击右上角即可分享
微信分享提示