Strings , I/O and formatting (Part-5 File I/O)

Let's start coding on what we have learnt in the previous post.
File f=new File("me.txt");
System.out.println(f.exists());
Here we created a File object and checked for the presence of the file using f.exists() method.If you don't have a me.txt inside the project folder this gives false as the output and if you do have true as the output.Let's move on and create a new file.
boolean a = f.createNewFile();
System.out.println(a+" "+f.exists());
Here we created a new file and check whether the process is successfully finished and the file is created.Note that createNewFile() creates a new file if it doesn't already exists.If the file exists you get false as the output from the above method. One thing to remember is that you have to put the file operation codes inside a try catch block as the operations declare checked exceptions.Alright...!!now we'll start writing text to files.
File f=new File("me.txt");
FileWriter writer = new FileWriter(f);
writer.write("I am Hasitha");
writer.flush();
writer.close();
We have created a file and written some text on it.Note that this is not the best way to write something in a file.The best way is to wrap the FileWriter inside a BufferedWriter and start the writing process.Anyway now all we have to do is reading the file.
char letters[]=new char[40];
FileReader reader = new FileReader(f);
int count = reader.read(letters);
for(char c:letters){
     System.out.println(c);
}
reader.close();
Okay the code is pretty straight forward.The output is "I am Hasitha". So let's talk about the unseen part here.What on earth is flush() and close(). When you write data out to an external stream there's some amount of buffering will occur.But you don't know for sure when was the last of the data will actually be sent.You can do file writings as much as possible and flush method guarantees that the last data chunk that you thought you had actually written gets out to the file.As you are using limited resources from the operating system invoking close method will release those resources and free up the memory.

Hmmm...Is it over now.No..Not until you learn how to combine(wrap) higher level BufferedReader and BufferedWriter with FileReader and FileWriter. Without moving to another post let's end the fun part here.
File file = new File("me.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String data = br.readLine();
Awesome..!!!!You got it right.No need to explain anything."Simple and straightforward".

Comments

  1. My channel.twitch: youtube, channel, channel, comments
    My channel.twitch.tv is a unique channel where you 4k youtube to mp3 can stream games and stream live streams of the best games and tournaments played by a real player.

    ReplyDelete

Post a Comment