java 文件读取 butter_Java开发网 - 写入RandomAccessFile文件时,怎样换行?

本文介绍了如何使用Java的RandomAccessFile进行文件读写操作,特别是涉及字节序列的处理。在示例代码中,创建了一个Employee类并尝试写入文件,然后读取文件内容。在读写过程中,遇到的问题是如何处理换行和getBytes()方法的含义。当name字段包含中文字符时,输出可能出现问题,提示了可能需要更深入理解CharsetEncoder的作用来解决编码问题。
摘要由CSDN通过智能技术生成

import java.io.*;

public class RandomFileTest

{

public static void main(String [] args) throws Exception

{

Employee e1 = new Employee("zhangsan",23);

Employee e2 = new Employee("lisi",22);

Employee e3 = new Employee("wangwu",21);

RandomAccessFile ra = new RandomAccessFile("c:\\1.txt","rw");

ra.write(e1.name.getBytes());

ra.writeInt(e1.age);

ra.write(e2.name.getBytes());

ra.writeInt(e2.age);

ra.write(e3.name.getBytes());

ra.writeInt(e3.age);

ra.close();

RandomAccessFile raf = new RandomAccessFile("c:\\1.txt","r");

int len = 8;

raf.skipBytes(12);  //跳过第一个员工的信息,其中姓名8字节,年龄4字节

System.out.println("第二个员工信息:");

String str = "";

for(int i = 0;i < len;i++)

{

str = str + (char)raf.readByte();

}

System.out.println("name:" + str);

System.out.println("age:" + raf.readInt());

System.out.println("第一个员工信息:");

raf.seek(0);  //将文件指针移到文件开始位置

str = "";

for(int i = 0;i < len;i++)

{

str = str + (char)raf.readByte();

}

System.out.println("name:" + str);

System.out.println("age:" + raf.readInt());

System.out.println("第三个员工信息:");

raf.skipBytes(12);

str = "";

for(int i = 0;i < len;i++)

{

str = str + (char)raf.readByte();

}

System.out.println("name:" + str);

System.out.println("age:" + raf.readInt());

raf.close();

}

}

class Employee

{

String name;

int age;

final static int LEN = 8;

public Employee(String name,int age)

{

if(name.length()>LEN)

{

name = name.substring(0,8);

}

else

{

while(name.length()

name = name +"\u0000";

}

this.name = name;

this.age = age;

}

}

ra.write(e1.name.getBytes());中getBytes()是什么意思?

SDK是这样说的:

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

我还是看不太懂。如果e1.name为中文,输出就有点问题,这是什么?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值