import java.io.File;
import java.util.Objects;
import java.util.Scanner;
public class Q1 {
public Q1(String filename) {
File file = new File(filename);
if (!file.exists()) {
System.out.println("你输入的"+file.getName()+"目录有误。");
} else {
for (String name : Objects.requireNonNull(file.list())) {
System.out.println(name);
}
}
}
public static void main(String[] args) {
String filename = new Scanner(System.in).nextLine();
new Q1(filename);
}
}
使用随机文件流类RandomAccessFile将一个txt文本文件倒序读出显示在控制台。
GBK编码中文占两个字节,UTF-8编码中文三个字节,在本程序中对使用UTF-8的编码的txt文件进行处理。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Q2 {
public Q2(String filename) throws IOException {
File file = new File(filename);
RandomAccessFile raf = new RandomAccessFile(file,"r");
long length = raf.length();
StringBuffer buffer = new StringBuffer();
while (length > 0) {
length--;
// 转到length的位置
raf.seek(length);
int c = (int)raf.readByte();
if (c >= 0 && c <= 255) {
buffer.append((char)c);
}else {
// UTF-8编码中文三个字节
length = length - 2;
// 对GBK编码的txt文件处理
// length--;
raf.seek(length);
byte[] character = new byte[3];
// GBK编码
// byte[] character = new byte[2];
// 读取中文的三个字节
raf.read(character);
buffer.append(new String(character));
}
}
System.out.println(buffer);
}
public static void main(String[] args) {
try {
new Q2("D:/test.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}



