微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

倒置读出文本文件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){
			
		}
	
	}
}

原文地址:https://www.jb51.cc/javaschema/284532.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐