|
How to read file upside/down |
|
|
The example below reads a file from bottom to top in reverse
way. If last line of file is 'hello', it will read 'olleh'. Two methods
are used to implement above mentioned functionality. The first
one is readinf file into character array and reversing it and the
second is using RandomAccessFile and FileChannel.
import java.io.*;
import java.nio.channels.*;
import java.nio.*;
public class FileReaderDownToUp {
public static void main(String[] args) {
try {
//method 1
File f = new File("hello.txt");
FileReader fr = new FileReader(f);
char[] c = new char[(int)f.length()];
char[] cnew = new char[(int)f.length()];
StringBuffer sbuf = new StringBuffer();
fr.read(c,0,(int)f.length());
int len = (int)f.length();
for (int i = 0, j = len - 1; i < len ; i++, j--) {
cnew[i] = c[j];
sbuf.append(cnew[i]);
}
System.out.println(sbuf.toString());
fr.close();
//method 2
/*
RandomAccessFile f = new RandomAccessFile("hello.txt","rw");
FileChannel fc = f.getChannel();
// map file to buffer
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,
0, f.length());
int len = (int)f.length();
for (int i = 0, j = len - 1; i < j; i++, j--)
{
byte b = mbb.get(i);
mbb.put(i, mbb.get(j));
mbb.put(j, b);
}
// finish up
fc.close();
*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.