Reputation: 1045
I am a newbie and I really want to learn the concept instead of just copying and pasting code. I wanted to learn how exactly to use the Jave IO and was confused and disapointed to see so my different versions of code.
So I made my own notes and wanted to confirm with the experts here whether I got it right. these are just for my own reference. I know is not perfect but I would appreciate if you could confirm whether they are correct.
Use BufferedWriter and FileWriter to write a text file ( as characters). Disadvantage is you cannot write a primitive data type.
Ex:
BufferedWriter bw= new BufferedWriter (new FileWriter("a.txt", true));
String x;
while ((x=bw.readLine())!=null){
bw.newLine();
bw.write(x);
bw.flush();}
Use BufferedReader and FileReader to read a text file (as characters)
Ex:
BufferedReader br = new BufferedReader (new FileReader("b.txt"));
String x;
while ((x=br.readLine())!=null){
System.out.println(x);}
Use DataOutputStream and FileOutputStream to write to a text file (in binary). Advantage is you can write primitive data types as well as strings.
Ex:
DataOutputStream dos = new DataOutputStream(new FileOutputStream("out.txt"));
dos.writeInt(cityIdA); // int cityIdA = 9897;
dos.writeUTF(cityNameA); // String cityNameA = "Green Lake City";
dos.writeInt(cityPopulationA); // int cityPopulationA = 500000;
dos.writeFloat(cityTempA); // float cityTempA = 15.50f;
dos.flush();
Use DataInputStream and FileInputStream to read a text file (in binary). Advantage is you can read primitive data types as well as strings.
Ex:
DataInputStream dis = new DataInputStream(new FileInputStream("inp.txt"));
int cityId1 =dis.readInt(); // int cityIdA = 9897;
String cityName1 =dis.readUTF(); // String cityNameA = "Green Lake City";
int cityPopulation1 =dis.readInt(); // int cityPopulationA = 500000;
float cityTemperature1 =dis.readFloat(); // float cityTempA = 15.50f;
Actual code:
import java.io.*;
class b{
public static void main (String args[]) throws IOException{
int cityIdA = 9897;
String cityNameA = "Green Lake City";
int cityPopulationA = 500000;
float cityTempA = 15.50f;
BufferedWriter bw = new BufferedWriter(new FileWriter("shahar.txt"));
bw.write("9897");
bw.write("Green Lake City");
bw.write("500000");
bw.write("15.50");
bw.flush();
bw.close();
DataOutputStream dos = new DataOutputStream(new FileOutputStream("out.txt"));
dos.writeInt(cityIdA);
dos.writeUTF(cityNameA);
dos.writeInt(cityPopulationA);
dos.writeFloat(cityTempA);
dos.flush();
BufferedReader br = new BufferedReader (new FileReader("shahar.txt"));
String x;
while ((x=br.readLine())!=null){
System.out.println(x);}
DataInputStream dos1 = new DataInputStream(new FileInputStream("out.txt"));
int cityId1 = dos1.readInt(); // int cityIdA = 9897;
System.out.println( cityId1);
String cityName1 =dos1.readUTF(); // String cityNameA = "Green Lake City";
System.out.println(cityName1);
int cityPopulation1 =dos1.readInt(); // int cityPopulationA = 500000;
System.out.println(cityPopulation1);
float cityTemperature1 =dos1.readFloat(); // float cityTempA = 15.50f;
System.out.println(cityTemperature1);
}
}
Upvotes: 3
Views: 960
Reputation: 951
I'm not so sure that your question is formatted in a way that will receive beneficial answers.
I could say:
"In your first example:
BufferedWriter bw= new BufferedWriter (new FileWriter("a.txt", true));
String x;
while ((x=bw.readLine())!=null) {
bw.newLine();
bw.write(x);
bw.flush();
}
bw.readLine()
is not correct. BufferedWriter is a writer class - it does not contain a readLine() method. You should use BufferedReader to read from a file.
The rest of your examples are "correct," besides the blatantly wrong code indentation."
But saying that wouldn't really help you out in the bigger picture. The way you've written your question leads me to believe that you're beginning to learn java and possibly new to programming in general: that's fine. However, I do not think this is fine:
...[I] was confused and disappointed to see so many different versions of code... So I made my own
That is not good. While it may be overwhelming to see so many different ways to accomplish one goal, programming has no "correct" way to do things (in most cases.. no need to argue semantics with a beginner). The Java API's give you methods and tools that do something. In the scope of beginner programming, you shouldn't worry about what is "correct" when it comes to using the methods themselves - you should simply be familiarizing yourself with the methods and understanding that these methods do something and I can tie them together logically to accomplish a goal.
You could look up "how to write to a file" and get hundreds of examples that are all different from each other - what happens when another person googles "how to read from a file" and stumbles upon this very StackOverflow question and reads your notes? We can throw your notes in the pile of "yet another slightly different version of code that reads from a file."
Normally, I would say that having some notes on how to do something like this is fine - if you were taking a programming course and would be tested on it verbatim. In your case, I would discourage it. I feel (keyword feel... I could be wrong) that you're going to compile your notes, start programming, say "I need to read something from a file, how do I do that again?" and then copy/paste the code from your notes. That doesn't teach you anything. You need to think "I know the BufferedReader class can be used to read from files - let me look at the javadocs and think of a logical way to apply its methods to read from a file in this specific case."
The JavaDocs are your friend. You will learn much more much faster if you don't use "notes" and simply write practice programs to familiarize yourself with using the API. I would argue that such "notes" are counterproductive to actually becoming a proficient programmer of any language.
Sorry if i'm completely off base in answering in the way I have. Just lookin' out for you. Maybe memorizing notes verbatim is your way of learning. That's cool too. Just remember that when you say I would appreciate if you could confirm whether [this code is] correct.
"correct" has no real meaning. The code works. Knowing why the code works (Or learning to just run the code yourself to see what happens and fix it if it doesn't work...) is far more important.
Good luck!
Upvotes: 1
Reputation: 13196
Your code subjectively has stylistic issues. I'll drop your examples here as though I wrote them myself.
(I put this before example 1 for a reason)
BufferedReader br = new BufferedReader (new FileReader("b.txt"));
String x;
while ((x = br.readLine()) != null)
{ // changed style, but otherwise fine
System.out.println(x);
}
// borrowed reader from example 1
BufferedReader br = new BufferedReader (new FileReader("b.txt"));
BufferedWriter bw = new BufferedWriter (new FileWriter("a.txt", true));
String x;
// this part didn't work. You were trying to read from a writer, as you write to it.
// if this were an object capable of reading and writing at the same time, you would
// run into issues because they wouldn't be rewinding after each operation and you'd
// end up with a combination of unexpected mirrored lines and garbled crap.
// changed loop to read from reader. reads data from one file, line by line, and
// writes to another.
while ((x = br.readLine()) != null)
{
bw.write(x); // in the other order, file will start with a blank line
bw.newLine(); // in this order, file will end with one instead
}
bw.flush(); // its better if this is not in the loop
Examples 3 and 4 are fine. You would use something like this if you needed to write lots of primitive types to a binary file. The other examples are much more suited for reading text.
Since you're a newbie, I'll give you some random advice too:
Upvotes: 3