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); //打印看看成功了没~
推荐阅读
-
java 文件的写入和读取
-
java读取文件和写入文件的方式 博客分类: JAVA
-
RandomAccessFile读取、写入txt文件
-
【java IO】使用Java输入输出流 读取txt文件内数据,进行拼接后写入到另一个文件中
-
Java读取、写入txt文件
-
C++输入输出流(读取,写入,复制文件)
-
python读取,写入txt文件
-
python 文件追加写入_Python写入文件–解释了打开,读取,追加和其他文件处理功能...
-
通过codehaus来实现json写入文件和读取文件成json对象 博客分类: javajson jsonjacksoncodehaus对象java
-
C#读取txt文件