package IO;
import java.io.*;
public class RandomAcessFileDemo {
public static void main(String[] args) throws Exception {
File f=new File("D:"+File.separator+"text.txt");
RandomAccessFile raf=null;
raf=new RandomAccessFile(f,"rw");
String name=null;
int age=0;
name="zhangsan";
age=15;
raf.writeBytes(name);
raf.skipBytes(8);
raf.writeInt(age);
raf.close();
}}
这儿使用RandomAccessFile流把字符串和int型数据写入到text.txt中
查看时,字符串没有乱码,int型数据变成了乱码。这儿该怎么解决,使
int型数据也能写入?
import java.io.*;
public class RandomAcessFileDemo {
public static void main(String[] args) throws Exception {
File f=new File("D:"+File.separator+"text.txt");
RandomAccessFile raf=null;
raf=new RandomAccessFile(f,"rw");
String name=null;
int age=0;
name="zhangsan";
age=15;
raf.writeBytes(name);
raf.skipBytes(8);
raf.writeInt(age);
raf.close();
}}
这儿使用RandomAccessFile流把字符串和int型数据写入到text.txt中
查看时,字符串没有乱码,int型数据变成了乱码。这儿该怎么解决,使
int型数据也能写入?
import java.io.*;public class RandomAcessFileDemo {
public static void main(String[] args) throws IOException {
File f = new File("C:" + File.separator + "text.txt");
int length = 0;
RandomAccessFile raf = null;
// 写入
try {
raf = new RandomAccessFile(f, "rw");
String name = "张三";
int age = 15;
byte[] bs = name.getBytes("utf-8");
length = bs.length;
raf.write(bs);
raf.writeInt(age);
} finally {
if (raf != null) {
raf.close();
raf = null;
}
} // 读取
try {
raf = new RandomAccessFile(f, "rw");
byte[] buffer = new byte[1024];
int len = raf.read(buffer, 0, length); // 上面输入的名字的长度
System.out.println("name:" + new String(buffer, 0, len, "utf-8"));
int age = raf.readInt();
System.out.println("age:" + age);
} finally {
if (raf != null) {
raf.close();
raf = null;
}
}
}
}
import java.io.File;
import java.io.RandomAccessFile;public class RandomAcessFileDemo {
public static void main(String[] args) throws Exception {
File f = new File("temp.txt");
RandomAccessFile raf = null;
raf = new RandomAccessFile(f, "rw");
String name = "zhangsan";
Integer age = 15;
raf.writeBytes(name);
raf.skipBytes(8);
raf.writeInt(age);
raf.seek(0);//找位置
byte[] b = new byte[8];
raf.read(b);
System.out.println(new String(b));
System.out.println(raf.readInt());
raf.close();
}}