倒置读出文本文件JAVA实现

预备知识:ASCII码(包括其扩展在内共256个)在UNICODE编码上的位置为0~255.

ASCII码是单字节的,其他UNICODE编码如中文是双字节的。

文本文件的换行包括回车符(CR,13)和换行符(LF,10),因此每次换行也是双字节。括号内为对应ASCII字符与ASCII编码。

如:

HelloWorld
1

占13个字节。

预备倒置读出的文本文件english.txt:

The arrow missed the target.
They rejected the union demand.
Where does this road go to?

下面是用随机流实现文本倒置输出方法,主要利用随机流特有的seek()方法定位在文件中的位置。

import java.io.*;
public class TxtReaderMain {
	public static void main(String[] args) {
		RandomAccessFile r;
		try {
			r = new RandomAccessFile("english.txt","rw");
			r.seek(0);
			long p = r.length();
			p--;
			while (p >= 0) {
				r.seek(p);
				int c = r.readByte();
				if (c <= 255 && c >= 0)       //判断是否单字节ASCII码
					System.out.print((char) c);
				else {                         //假如是双字节UNICODE编码,比如中文
					p--;
					r.seek(p);
					byte[] bb = new byte[2];
					r.read(bb);
					System.out.println(new String(bb));
				}
				p--;
			}
		} catch (Exception e) {
		}
	}

}
结果:

?ot og daor siht SEOd erehW


.dnamed noinu eht detcejer yehT


.tegrat eht dessim worra ehT

当然,也可以直接直接用字符输入流得到相同结果:

import java.io.*;
public class ReadMain {
	public static void main(String[] args) {
		try{FileInputStream f=new FileInputStream("english.txt");
		byte[] bb=new byte[100];
		int n=f.read(bb);
		char[] c=new String(bb,n).tochararray();
		//System.out.println(c);
		for(int i=c.length-1;i>=0;i--)
			System.out.print(c[i]);
		}catch(Exception e){
			
		}
	
	}
}

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...