In C, C++, we have the option to make FILE pointer to point the last byte and make reverse read by decreasing pointer position. However, we do not have option to do the same in Java using pre-existing InputStream or Reader in JAVA SE.
One of the classic cryptography uses reverse the file content and share to the receiver. Receiver also needs to reverse the content and understand the meaning. If we would like to do the same in computer, reversing algorithm useful. However, just reversing will not help we have several mechanism to protect the message over network in modern cryptography.
If we ask our friends to write reversing program, most of them will write a program, in which content first read and put it into bytes or character array and then reverse order will be stored in another byte or character array. This program perform not good for bigger files.
Reader content reversing
To reverse content from java.io.Reader, we do not require char array. We can use StringBuilder which helps us to append/insert content in any index place. Read character one by one from Reader and insert at ZERO location, which will reverse the content.
InputStream content reversing
In InputStream, we have an API available() which gives the content length. byte array will be created using this length. Read bytes from this InputStream and store in byte array with reverse order
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
public class ReverseReaderTest {
public static void main(String[] args)
throws Exception {
File f = new File("/tmp/sample.txt");
FileReader fr = new FileReader(f);
System.out.println("Using Reader: \n" + reverseRead(fr));
InputStream is = new FileInputStream(f);
System.out.println("Using InputStream:\n" + reverseRead(is));
}
/**
* Reverse read using Reader
*
* @param reader
* @return
* @throws IOException
*/
public static String reverseRead(Reader reader)
throws IOException {
StringBuilder sb = new StringBuilder();
int ch = -1;
while ((ch = reader.read()) != -1) {
sb.insert(0, (char) ch);
}
return sb.toString();
}
/**
* Reverse read using InputStream
*
* @param is
* @return
* @throws IOException
*/
public static String reverseRead(InputStream is)
throws IOException {
int length = is.available();
byte[] bytes = new byte[length];
int ch = -1;
while ((ch = is.read()) != -1) {
bytes[--length] = (byte) ch;
}
return new String(bytes);
}
}
Assume, if sample.txt has the content as Hello World
, output looks like below
Using Reader:
dlroW olleH
Using InputStream:
dlroW olleH
1 comment:
This information is quite useful, I truly enjoyed. Thanks for this blog.
core java training in chennai
core java Training in Porur
C++ Training
C Language Training
javascript training in chennai
javascript course in chennai
core java Training in Adyar
clinical sas training in chennai
Post a Comment