博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java字符流入门
阅读量:660 次
发布时间:2019-03-15

本文共 1828 字,大约阅读时间需要 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/

你可能感兴趣的文章