10.RandomAccessFile
发表日期:2022-08-05 16:09:05 | 来源: | | 浏览(965) 分类:JAVA基础
RandomAccessFile
package File;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("D:" + File.separator + "RandomAccessFile.txt");
//两种写法均可
//RandomAccessFile rFile = new RandomAccessFile("D:"+File.separator+"test.txt", "rw");
RandomAccessFile rFile = new RandomAccessFile(file, "rw");
String string = "abcdefg我去这是什么情况?";
;
rFile.write(string.getBytes());//写入中文会乱码
rFile.close();
write();
read();
}
private static void read() {
// TODO Auto-generated method stub
File file = new File("d:" + File.separator + "123.txt");
RandomAccessFile rFile = null;
try {
rFile = new RandomAccessFile(file, "r");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
byte c[] = new byte[(int) rFile.length()];
rFile.read(c);
System.out.println(new String(c));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void write() {
File file = new File("d:" + File.separator + "123.txt");
RandomAccessFile rFile = null;
try {
rFile = new RandomAccessFile(file, "rw");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String name = "zhangsan";
int age = 30;
try {
rFile.writeInt(age);
// rFile.writeBytes(name);
rFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}- JAVA(0)
- JAVA基础(30)
- 1.JAVA开发环境配置(0)
- 2.java数据类型(0)
- 3.数组(0)
- 4.Date(0)
- 5.String 和 StringBuffer类常用方法(0)
- 6.Math类(0)
- 7.Cloneable(0)
- 8.File 文件(0)
- 9.FileReader和FileWriter(0)
- 10.RandomAccessFile(0)
- 11.FileInputStream和FileOutputStream(0)
- 12.InputStreamReader和OutputStreamWriter(0)
- 13.BufferedReader(0)
- 14.Scanner(0)
- 15.DataOutputStream(0)
- 16.Thead 多线程(0)
- 17.TimerTask(0)
- 18.zip(0)
- 19.Charset(0)
- 20.List(0)
- 21.Map(0)
- 22.Properties(0)
- 23.Enumeration(0)
- 24.Collection(0)
- 25.JDBC(0)
- 26.Iterator(0)
- 27.Abstract(0)
- 28.Interface(0)
- 29.Serializable(0)
- 30.Camparable(0)
- JSP基础(50)
宁公网安备 64010402001209号