zoukankan      html  css  js  c++  java
  • IO流-文件的写入和读取

    1、文件写入

    类:

      FileWriter继承自Writer(字符流基类之一,另外一个为Reader)

    方法:

      writer(参数); 根据参数可以写入字符、字符数组、字符数组中的一部分、整型、字符串、字符串中的一部分,抛IOException

      flush(); 刷新内存,把内存中的字符流写入文件

      close(); 刷新内存并关闭字符输入流,抛出IOException

    import java.io.*;
    
    class Test
    {
        public static void main(String[] args)
        {
            //这是在jdk1.7引入的可以隐性的调用close()方法,FileWriter在创建时抛出IOException
            try(FileWriter fileWriter = new FileWriter("Test.txt"))
            {
                fileWriter.write("你好");
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
    
        }
    }
    /*这是不用新方式写,很繁琐
    FileWriter fileWriter = null;
    try()
    {
        fileWriter = new FileWriter("Test.txt");
        fileWriter.write("你好");
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try()
        {
            fileWriter.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    */

    注:FileWriter在创建时,若文件存在,创建同名空文件覆盖之,若不存在创建,若想添加的话用一下构造方法

      FileWriter fileWriter = new FileWriter("文件名", ture);  设定添加为true

    2、文件读取

    类:

      FileReader 继承自Reader, java.io包

    方法:

      read(参数); 可以读取一个字符,也可以读取字符数组,也可以读取字符数组的一部分

      close(); 关闭字符输入流

    代码举例:

    class Test
    {
        public static void main(String[] args)
        {
          //FileReader构造方法创建一个与所读取文件关联的一个字符输入流
            try(FileReader fileReader = new FileReader("Test.txt"))
            {
                char[] charFile = new char[1024];
                int charNum = fileReader.read(charFile);
                System.out.print(new String(charFile, 0, charNum));
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    使用MTA HTML5统计API来分析数据
    .NET Core下操作Git,自动提交代码到 GitHub
    EPPlus.Core 处理 Excel 报错之天坑 WPS
    利用SQL生成模型实体类
    基于.NET Core开发的个人博客发布至CentOS小计
    Windows下MySQL安装流程,8.0以上版本ROOT密码报错及修改
    Redis快速入门及使用
    一些不错的网站
    一些精简的JavaScript代码集合
    MongoDB Shell 命令
  • 原文地址:https://www.cnblogs.com/fantasy01/p/3995902.html
Copyright © 2011-2022 走看看