aspose file tools*
The moose likes I/O and Streams and the fly likes Reading a text file in binary Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Reading a text file in binary" Watch "Reading a text file in binary" New topic
Author

Reading a text file in binary

JC Denton
Greenhorn

Joined: Nov 21, 2004
Posts: 6
Im trying to read a text file saved in ASCII in binary but the string thats supposed to contain the data does not contain anyting... where am I going wrong?

Note: most of the code is copied from Ivor Horton's beginning Java sdk 1.4

public static void readFile(String path) {
String myString = "";
filePath = new File(path);
myString = filePath.toString();
System.out.println(myString + "\n" + filePath);
//testing stuff
FileInputStream inFile = null;
File aFile = new File(path);

try {
inFile = new FileInputStream(aFile);
} catch (FileNotFoundException e) {
e.printStackTrace(System.err );
System.exit(1);
//1? how is 1 different from 0?
}
FileChannel inChannel = inFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate((int)filePath.length());
//small file expected so I created a buffer the size of that file
//what exception will be thrown if the integer overflows?
try {
myString = ((ByteBuffer)(buf.flip())).asCharBuffer().toString();
//flip??
System.out.println(myString);
//should now contain the file contents
buf.clear();
inFile.close();
//suits me
}catch(IOException e) {
System.out.println( "Couldn't open the files: " + e );
e.printStackTrace(System.err);
//no exceptions are printed when the file is run
System.exit(1);
}
System.exit(0);
}

In the final version of the program the file should be located in the same directory as the program. How do I find where the program is located?
Thanx all


<b>I know nothing</b> - Manuel Fawlty Towers
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8908
    
    8


//1? how is 1 different from 0?

By convention, a non-zero return value indicates an error. Useful if invoking a program from a shell script or other program.


//small file expected so I created a buffer the size of that file
//what exception will be thrown if the integer overflows?

None. You just lose precision.


//flip??

flip. From the
java.nio.BufferJava 1.4 API Documentation (get familiar with it!):

Flips this buffer. The limit is set to the current position and then the position is set to zero.

So it sets you up to process the data you (should have) read in from the file.


How do I find where the program is located?

"Program"s in Java are .class files which contain a method with the signiture:


As for your big question, why you don't see data, perhaps the Java API Doc for FileChannel will help.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reading a text file in binary