RandomAccessFile r = new RandomAccessFile("C:\\Users\\DELL\\Desktop\\123.txt","r"); RandomAccessFile w = new RandomAccessFile("C:\\Users\\DELL\\Desktop\\1234.txt","rw"); String string = r.readLine(); String s = new String(string.getBytes("ISO-8859-1")); for(int i = 0;i < index - 1;i++){ System.out.println(s); w.writeUTF(s+"\r\n"); string = r.readLine(); s = new String(string.getBytes("ISO-8859-1")); } 生成的1234.txt文件每行前面都有两个乱码
时间: 2023-06-20 07:09:43 浏览: 47
这个问题很可能是因为你使用了`writeUTF()`方法,它会在写入字符串之前写入两个字节的长度信息。这样会导致生成的文件每行前面都有两个乱码。
你可以尝试改用`write()`方法,它会直接写入字符串的字节表示,而不会加入长度信息。例如:
```
w.write(s.getBytes("ISO-8859-1"));
w.write("\r\n".getBytes("ISO-8859-1"));
```
这样就可以避免生成的文件每行前面出现乱码了。
相关问题
RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile, "rw") 报错permission denied
RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile, "rw") 报错 permission denied 是因为你没有足够的权限来访问锁文件。这可能是由于文件所在目录的权限设置不正确导致的。要解决这个问题,你可以尝试以下几种方法:
1. 检查文件所在目录的权限:确保你有足够的权限来访问该目录。你可以使用以下命令来检查和修改目录的权限:
```shell
ls -l /path/to/directory
chmod +rwx /path/to/directory
```
2. 检查文件的所有者和组:确保文件的所有者和组与你当前的用户匹配。你可以使用以下命令来检查和修改文件的所有者和组:
```shell
ls -l /path/to/file
chown your_user:your_group /path/to/file
```
3. 检查文件的锁定状态:如果你确定没有其他进程正在使用该锁文件,你可以尝试删除锁文件并重新运行程序。但请注意,这可能会导致其他问题,因此在删除锁文件之前最好备份它。
如果以上方法都无法解决问题,你可能需要联系系统管理员或开发人员以获取进一步的帮助。
给下列代码加上注释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) { } } }
// 指定包名
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) {
// 异常处理
}
}
}