| Author |
File navigation and I/O
|
sonia jaswal
Ranch Hand
Joined: Jun 01, 2007
Posts: 42
|
|
Code: import java.io.*; class Writer2 { public static void main(String [] args) { char[] in = new char[50]; // to store input int size = 0; try { File file = new File( // just an object "fileWrite2.txt"); FileWriter fw = new FileWriter(file); // create an actual file // & a FileWriter obj fw.write("howdy\nfolks\n"); // write characters to // the file fw.flush(); // flush before closing fw.close(); // close file when done FileReader fr = = new FileReader(file); // create a FileReader // object size = fr.read(in); // read the whole file! System.out.print(size + " "); // how many bytes read for(char c : in) // print the array System.out.print(c); fr.close(); // again, always close } } catch(IOException e) { } } } which produces the output: 12 howdy folks // here, the following para is a limitation for the previous code.... which i did not understand... can someboidy please explain it to me... "When we were reading data back in, we put it into a character array. It being an array and all, we had to declare its size beforehand, so we'd have been in trouble if we hadn't made it big enough! We could have read the data in one character at a time, looking for the end of file after each read(), but that's pretty painful too." Apart from this... please tell me what does reading the file's contents back into memory mean.... thank you....
|
 |
Pranav Bhatt
Ranch Hand
Joined: Mar 20, 2006
Posts: 283
|
|
"When we were reading data back in, we put it into a character array. It being an array and all, we had to declare its size beforehand, so we'd have been in trouble if we hadn't made it big enough! We could have read the data in one character at a time, looking for the end of file after each read(), but that's pretty painful too."
They meant to say that they have read the contents of the file they have created as file into an character array named as in as in the following line-: size = fr.read(in);. as you can see the size is 12. If they have not declared array size as 50, large enough to hold 12 chars, we would have end up with arrayOutofBound exception if it was less then 12. Reading back implies we are reading the contents we wrote in a file. Thanks
|
 |
 |
|
|
subject: File navigation and I/O
|
|
|