Cannot read last byte of a file...."
I have a text file named "abcd.txt"
It contains data as "abcdefghijklmnopqrstuvwxyz"
'
So....i need to print the last byte of a file . . that is "z" after program execution'
I just tried to read file and using seek function, i tried to print...'
But...it gives error..'
Plz help me to solve this....'
Thanx in advance...'
'
Code...
Code :
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class last_byte
{
public static void main(String args[]) throws FileNotFoundException, IOException
{
File rcfile=new File("D:/abcd.txt");
RandomAccessFile raf = new RandomAccessFile(rcfile,"rwd");
raf.seek(rcfile.length()-1);
char lb=raf.readChar();
System.out.print(lb);
}
}
'
Error...
Code :
Exception in thread "main" java.io.EOFException
at java.io.RandomAccessFile.readChar(RandomAccessFile.java:747)
at data.last_byte.main(last_byte.java:13)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Re: Cannot read last byte of a file...."
Read the API doc for the class's readChar() method and see if you are using it correctly.
What does it say it will do?
Re: Cannot read last byte of a file...."
Hi,
If you print rcfile.length(), It'll show 27, but this is 26 charachters in your abcd.txt file.
so if you put raf.seek(rcfile.length()-2); the problem will be solved.
may be there is an End of File charachter in text file that you can not see.
Note: It is better the class name starts with capital letter, e.g. Last_byte insted of last_byte
Re: Cannot read last byte of a file...."
@Banafshe....Thanx....it solved to some extent...'
Now, i dont get error...'
'
But instead of pronting "z"...it prints "祺"(some chinese character)'
'
Output...
Code :
祺
BUILD SUCCESSFUL (total time: 0 seconds)
Re: Cannot read last byte of a file...."
Are you insisting on using RandomAccessFile?
Why don't you use something else like this?
In this code, 10 is the last character in file.
Code :
import java.io.*;
public class last_byte
{
public static void main(String args[]) throws FileNotFoundException, IOException
{
File rcfile=new File("abcd.txt");
InputStream in = new FileInputStream(rcfile);
Reader reader = new InputStreamReader(in);
int intCh;
int theLastChar = 10;
while ((intCh = reader.read()) != -1) {
char ch = (char) intCh;
if (intCh != 10) {
theLastChar = ch;
}
}
System.out.println((char)theLastChar);
}
}
Re: Cannot read last byte of a file...."
Thanxx.....@Banafshe..'
It worked...'
Re: Cannot read last byte of a file...."
If you look at the contents of the file in a hex editor you will see what it contains.
Most files created with a text editor write out files with one character per byte.
If you save text in Unicode format (wordpad will do it) it will use two bytes per character.