美文网首页
RandomAccessFile读取、写入txt文件

RandomAccessFile读取、写入txt文件

作者: 恋上夜的黑 | 来源:发表于2017-11-06 23:31 被阅读63次

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);  //打印看看成功了没~

相关文章

网友评论

      本文标题:RandomAccessFile读取、写入txt文件

      本文链接:https://www.haomeiwen.com/subject/hkwrmxtx.html