• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reading a text file in binary

 
JC Denton
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Joe Ess
Bartender
Posts: 9302
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

//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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic