博客
关于我
java字符流入门
阅读量:663 次
发布时间:2019-03-15

本文共 1813 字,大约阅读时间需要 6 分钟。

字符流

操作文本文件可以选择用字符流

将数据写入文件

java写法

import java.io.*;public class Demo {       public static void main(String[] args) {           FileWriter fw = null;        try {               //创建FileWriter对象            fw = new FileWriter("./tmp.txt");            //向文件中写入内容            fw.write("abc");        } catch (IOException e) {               e.printStackTrace();        } finally {               try {                   assert fw != null;                //如果不为空,则关闭文件,释放资源                fw.close();            } catch (IOException e) {                   e.printStackTrace();            }        }    }}

scala写法

def fileWriterDemo: Unit = {       var fileWriter: FileWriter = null    try {         //创建文件输出流和文件相关联      //文件不存在会自动创建。默认在当前路径下创建。但是文件夹不会自动创建,比如写./data/tmp.txt ,如果data文件夹不存在,不会自动创建      fileWriter = new FileWriter("./tmp.txt")      //将字符串写入文件      fileWriter.write("abcdef")    } catch {         case e: Exception => println(e.printStackTrace())    } finally {         //关闭流之前要判断,避免空指针异常      if (fileWriter != null) fileWriter.close()    }  }

从文件读取数据

java写法

public static void ReadDemo() throws IOException {           //因为是文本,所以选择字符流,又因为是读取,所以使用字符输入流        //读取的文件必须事先存在        //创建文件输入流和文件相关联        FileReader fr = new FileReader("./tmp.txt");        int num;        //Reads a single character.        while ((num = fr.read()) != -1) {               //读取的是int,需要强制转型为char类型            System.out.print((char) (num));//abc        }    }

也可以读取内容到数组

public static void ReadDemo1() throws IOException {           FileReader fr = new FileReader("./tmp.txt");        char[] arr=new char[1024];        int num;        //Reads characters into an array.        //一次读取一个数组的内容来提高读取效率        while ((num=fr.read(arr))!=-1){               System.out.println(new String(arr));//abc        }    }

总结

  • 字符流可用于读取以及写入文本文件

转载地址:http://nosmz.baihongyu.com/

你可能感兴趣的文章
Netty源码—5.Pipeline和Handler二
查看>>
Netty源码—6.ByteBuf原理一
查看>>
Netty源码—6.ByteBuf原理二
查看>>
Netty源码—7.ByteBuf原理三
查看>>
Netty源码—7.ByteBuf原理四
查看>>
Netty源码—8.编解码原理一
查看>>
Netty源码—8.编解码原理二
查看>>
Netty源码解读
查看>>
netty的HelloWorld演示
查看>>
Netty的Socket编程详解-搭建服务端与客户端并进行数据传输
查看>>
Netty的网络框架差点让我一夜秃头,哭了
查看>>
Netty相关
查看>>
Netty简介
查看>>
Netty线程模型理解
查看>>
netty解决tcp粘包和拆包问题
查看>>
Netty速成:基础+入门+中级+高级+源码架构+行业应用
查看>>
Netty遇到TCP发送缓冲区满了 写半包操作该如何处理
查看>>
netty(1):NIO 基础之三大组件和ByteBuffer
查看>>
Netty:ChannelPipeline和ChannelHandler为什么会鬼混在一起?
查看>>
Netty:原理架构解析
查看>>