欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RandomAccessFile读取、写入txt文件

程序员文章站 2024-03-18 17:53:46
...

Java学习第23天,学习到了用API写入和读取txt文件,或许实际中用法挺多的,为避免自己忘记,记录用法:

String file="D:/demo.txt";   //导入文件,转string
RandomAccessFile raf=new RandomAccessFile(file,"rw");//新建文件管理对象, 设置权限
String str="中国"; //要写入的string
byte[] bytes=str.getBytes("UTF-8");//转化为utf-8
raf.write(bytes); //将bytes数组中的数据一起写到文件中
        //for (byte b : bytes) {
        //  raf.write(b);             //备注一个单次循环写入方法
        //}
raf.close();//文件管理系统用完一定要关闭!

有写入,当然也需要读取

String file = "D:/demo.txt";
RandomAccessFile raf=new RandomAccessFile(file, "r");
byte[] bytes =new byte[(int)raf.length()];//数组的长度就是字符的长度

int i = raf.read(bytes);//从文件中批量读取数据到byte数组

//      int i=0, b;
//      while((b=raf.read())!=-1){          //备注一个循环方法
//          bytes[i++]=(byte)b;
//      }

raf.close();//用完一定要关闭
String str = new String(bytes, "UTF-8"); //转化成str
System.out.println(str);  //打印看看成功了没~