倒置读出文本文件JAVA实现

前端之家收集整理的这篇文章主要介绍了倒置读出文本文件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()方法定位在文件中的位置。

@H_502_23@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.f2er.com/javaschema/284532.html

猜你在找的设计模式相关文章