给下列代码加上注释package ch1; import java.io.File; import java.io.RandomAccessFile; public class CH3 { public static void main(String args[]) { File f = new File("D:/text1.txt"); try (RandomAccessFile random = new RandomAccessFile(f, "rw");) { long m = random.length(); String t = "\n学号:xxx,姓名:xxx"; random.seek(m); byte a[] = t.getBytes(); random.write(a); random.seek(0); while (m >= 0) { m = m - 1; random.seek(m); int c = random.readByte(); if (c <= 255 && c >= 0) System.out.print((char) c); else { m = m - 1; random.seek(m); byte cc[] = new byte[2]; random.readFully(cc); System.out.print(new String(cc)); } } } catch (Exception exp) { } } }
时间: 2023-07-16 19:12:09 浏览: 105
// 指定包名
package ch1;
import java.io.File;
import java.io.RandomAccessFile;
public class CH3 {
public static void main(String args[]) {
// 创建文件对象
File f = new File("D:/text1.txt");
try (RandomAccessFile random = new RandomAccessFile(f, "rw");) {
// 获取文件长度
long m = random.length();
// 要写入的字符串
String t = "\n学号:xxx,姓名:xxx";
// 设置指针位置为文件末尾
random.seek(m);
// 将字符串转换成字节数组并写入文件
byte a[] = t.getBytes();
random.write(a);
// 重置指针位置为文件开头
random.seek(0);
// 逐个字节读取文件内容
while (m >= 0) {
m = m - 1;
random.seek(m);
int c = random.readByte();
// 如果是 ASCII 字符,则直接输出
if (c <= 255 && c >= 0)
System.out.print((char) c);
// 如果是中文字符,则读取两个字节并输出
else {
m = m - 1;
random.seek(m);
byte cc[] = new byte[2];
random.readFully(cc);
System.out.print(new String(cc));
}
}
} catch (Exception exp) {
// 异常处理
}
}
}
阅读全文