博客
关于我
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/

你可能感兴趣的文章
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx/Apache反向代理
查看>>
Nginx: 413 – Request Entity Too Large Error and Solution
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx: [error] open() “/usr/local/nginx/logs/nginx.pid“ failed (2: No such file or directory)
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx:objs/Makefile:432: recipe for target ‘objs/src/core/ngx_murmurhash.o‘解决方法
查看>>
nginxWebUI runCmd RCE漏洞复现
查看>>
nginx_rtmp
查看>>
Vue中向js中传递参数并在js中定义对象并转换参数
查看>>
Nginx、HAProxy、LVS
查看>>
nginx一些重要配置说明
查看>>
Nginx一网打尽:动静分离、压缩、缓存、黑白名单、跨域、高可用、性能优化......
查看>>
Nginx下配置codeigniter框架方法
查看>>
Nginx与Tengine安装和使用以及配置健康节点检测
查看>>
Nginx中使用expires指令实现配置浏览器缓存
查看>>
Nginx中使用keepalive实现保持上游长连接实现提高吞吐量示例与测试
查看>>