RandomAccessFile中writeInt()的使用问题

danwell7 2012-05-03 09:27:34
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型数据也能写入?
...全文
303 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
FFF9527 2012-05-03
  • 打赏
  • 举报
回复

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;
}
}
}
}
FFF9527 2012-05-03
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

我知道int型数据时4字节,当我使用RandomAccessFile类中的writeInt()写数据到文件中时,在用readInt()读取数据,输出结果时还会出现运行错误。这儿不应出现此种问题啊?
[/Quote]

应该是程序有误,试着调查一下
danwell7 2012-05-03
  • 打赏
  • 举报
回复
我知道int型数据时4字节,当我使用RandomAccessFile类中的writeInt()写数据到文件中时,在用readInt()读取数据,输出结果时还会出现运行错误。这儿不应出现此种问题啊?
nmyangym 2012-05-03
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

int使用的是一个4个字节保存的,想显示出来必须转换为字符串。。。
[/Quote]
+1
FFF9527 2012-05-03
  • 打赏
  • 举报
回复
int使用的是一个4个字节保存的,想显示出来必须转换为字符串。。。
sdojqy1122 2012-05-03
  • 打赏
  • 举报
回复

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();
}

}

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧