Java文件读写操作

Java文件读写操作Java中I/O流对文件的读写有很多种方法,在这里我主要介绍三种方式,供大家参考。第一种方式:使用FileWriter和FileReader,对文件内容按字符读取,代码如下Stringdir="E:\\soft\\aaa\\a.txt";Filefile=newFile(dir);//如果文件不存在,创建文件if(!file.exists())file.c…

大家好,又见面了,我是你们的朋友全栈君。

Java中I/O流对文件的读写有很多种方法,在这里我主要介绍三种方式,供大家参考。

第一种方式:使用FileWriter和FileReader,对文件内容按字符读取,代码如下

String dir = "E:\\soft\\aaa\\a.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists()) 
    file.createNewFile();
//创建FileWriter对象
FileWriter writer = new FileWriter(file);
//向文件中写入内容
writer.write("the first way to write and read");
writer.flush();
writer.close();

//创建FileReader对象,读取文件中的内容
FileReader reader = new FileReader(file);
char[] ch = new char[100];
reader.read(ch);
for(char c:ch) {
    System.out.print(c);
}
System.out.println();
reader.close();

第二种方式:使用包装类BuffredReader和BufferedWriter,对文件内容进行整行读取,代码如下

String dir = "E:\\soft\\aaa\\b.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists()) 
    file.createNewFile();
//创建BufferedWriter对象并向文件写入内容
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//向文件中写入内容
bw.write("the second way to write and read");
bw.flush();
bw.close();
//创建BufferedReader读取文件内容
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line=br.readLine())!=null) {
    System.out.println(line);
}
br.close();

第三种方式:使用FileInputStream和FileOutputStream,这种方法以字节的形式写入文件,读取文件时先读取字节数组,再将字节数组转换为字符串形式,代码如下:

String dir = "E:\\soft\\aaa\\c.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists()) 
    file.createNewFile();
//创建FileOutputStream对象,写入内容
FileOutputStream fos = new FileOutputStream(file);
//向文件中写入内容
fos.write("the third way to write and read".getBytes());
fos.close();
//创建FileInputStream对象,读取文件内容
FileInputStream fis = new FileInputStream(file);
byte[] bys = new byte[100];
while (fis.read(bys, 0, bys.length)!=-1) {
    //将字节数组转换为字符串
    System.out.println(new String(bys));
}
fis.close();

类中的整体代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileRW { 
   

    //第一种方式:使用FileWriter和FileReader
    public void firstWay() throws IOException {
        String dir = "E:\\soft\\aaa\\a.txt";
        File file = new File(dir);
        //如果文件不存在,创建文件
        if (!file.exists()) 
            file.createNewFile();
        //创建FileWriter对象
        FileWriter writer = new FileWriter(file);
        //向文件中写入内容
        writer.write("the first way to write and read");
        writer.flush();
        writer.close();

        //创建FileReader对象,读取文件中的内容
        FileReader reader = new FileReader(file);
        char[] ch = new char[100];
        reader.read(ch);
        for(char c:ch) {
            System.out.print(c);
        }
        System.out.println();
        reader.close();
    }

    //第二种方式:使用BuffredReader和BufferedWriter
    public void secondWay() throws IOException {
        String dir = "E:\\soft\\aaa\\b.txt";
        File file = new File(dir);
        //如果文件不存在,创建文件
        if (!file.exists()) 
            file.createNewFile();
        //创建BufferedWriter对象并向文件写入内容
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        //向文件中写入内容
        bw.write("the second way to write and read");
        bw.flush();
        bw.close();
        //创建BufferedReader读取文件内容
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while ((line=br.readLine())!=null) {
            System.out.println(line);
        }
        br.close();
    }

    //第三种方式:使用FileInputStream和FileOutputStream
    public void thirdWay() throws IOException {
        String dir = "E:\\soft\\aaa\\c.txt";
        File file = new File(dir);
        //如果文件不存在,创建文件
        if (!file.exists()) 
            file.createNewFile();
        //创建FileOutputStream对象,写入内容
        FileOutputStream fos = new FileOutputStream(file);
        //向文件中写入内容
        fos.write("the third way to write and read".getBytes());
        fos.close();
        //创建FileInputStream对象,读取文件内容
        FileInputStream fis = new FileInputStream(file);
        byte[] bys = new byte[100];
        while (fis.read(bys, 0, bys.length)!=-1) {
            //将字节数组转换为字符串
            System.out.println(new String(bys));
        }
        fis.close();
    }

    public static void main(String[] args) throws IOException {
        FileRW fileRW = new FileRW();
        fileRW.firstWay();
        fileRW.secondWay();
        fileRW.thirdWay();
    }
}

运行结果如下:

the first way to write and read
the second way to write and read
the third way to write and read

希望对大家有帮助,有什么问题欢迎提问

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/159368.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • dwcss样式中英对照_dw-cs5-css规则英汉对照表.docx

    dwcss样式中英对照_dw-cs5-css规则英汉对照表.docxdw-cs5-css规则英汉对照表.docx一、类型FONTFAMILY字体FONTSIZE字体大小FONTSTYLE字体风格,如斜体、正常等LINEHEIGHT行高(用来设定字行间距)FONTWEIGHT字体浓淡FONTVARIANT字体变量(用来设定字体是正常显示,还是以小型大写字母显示)TEXTTRANS文本转换(用来设定字体的大小写转换)TEXTDECORATION(字体装饰)UNDER…

    2022年5月17日
    44
  • java面试题及答案整理(解决方案经理面试题)

    2012年毕业,2016年转行,没有一个体面的工作,机缘巧合之下,来到了大连,Java培训,一个全新的领域,迷茫、困惑、漫无目的的努力,转行真的被歧视,真的不行吗?我命由我不由天,我觉得我行!相信我,只要你足够努力,总有成为架构师,独挡一面的一天。最近参加了一些面试,效果不是很理想,项目介绍只有大框,没有突出重点,没有项目中的具体细节,因为都是看的B站视频,实际工作中都是在做重复的CRUD工作,愁人啊。618买的新书塑料还没拆!视频计划已经执行到第二篇了!熬夜学习,是刻苦奋斗还是自欺欺人?面试

    2022年4月16日
    160
  • 硬阈值(Hard Thresholding)函数解读[通俗易懂]

    硬阈值(Hard Thresholding)函数解读[通俗易懂]题目:硬阈值(HardThresholding)函数解读1、硬阈值(HardThresholding)函数的符号    硬阈值(HardThresholding)并没有软阈值(SoftThresholding)那么常见,这可能是因为硬阈值解决的问题是非凸的原因吧。硬阈值与软阈值由同一篇文献提出,硬阈值公式参见文献【1】的式(11):     第一次邂逅硬阈值

    2022年6月12日
    58
  • 初次尝试使用VisualSFM记录

    初次尝试使用VisualSFM记录  对于SFM一直觉得高大上又神秘,一年前粗略的了解过一下,今年有时间尝试深入了解SFM,对于初学者来说,VisualSFM真的时非常好的感受SFM的免费软件,于是通过其他博客的指导(没去看官方的英文版,容易犯困),做了一个3D模型出来,感觉还挺好玩,记录一下。  实际上,VisualSFM只做了一部分工作,优化是用MeshLab做的,所以分两个环节:   1.VisualSF…

    2022年6月20日
    23
  • MySQL数据库使用命令行备份|MySQL数据库备份命令

    MySQL数据库使用命令行备份|MySQL数据库备份命令转至  神马和浮云 ,命令未测试,主要是方便操作mysql时需要而记的笔记  例如:数据库地址:127.0.0.1数据库用户名:root数据库密码:pass数据库名称:myweb 备份数据库到D盘跟目录mysqldump-h127.0.0.1-uroot-ppassmyweb>d:/backupfile.sql备份到当前目录备份MySQ…

    2022年6月10日
    33
  • java uniqueresult_关于query.uniqueResult报错问题

    java uniqueresult_关于query.uniqueResult报错问题publicfloatcountmonthmoney(Longblogid){java.text.SimpleDateFormatsf=newjava.text.SimpleDateFormat(“yyyyMM”);Stringtoday=sf.format(newjava.util.Date());StringBuilderstring…publicfloatcountmonthmone…

    2022年9月30日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号