Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and Writing to the same file simultaneously in java

How can I access data in my file without first closing my BufferedWriter?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class Tp {
    public static void main(String[] args) throws IOException{
        File f = new File("Store.txt");
        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        BufferedReader br = new BufferedReader(new  FileReader(f));
        bw.write("Some text");
        System.out.println(br.readLine());
        bw.write("Some more text");
        bw.close();
        br.close();
    }
}

The console is showing null. How do I fix this?

like image 650
Karan Kulwal Avatar asked Jun 19 '18 09:06

Karan Kulwal


People also ask

Can you read and write to the same file in Java?

You can't open the same file to read and write at the same time. You have to open and save the file information in a data structure and then close it. Then you have to work with the data structure in memory and open the file to write results. And when you finish to write you should close it.

What is difference between FileWriter and BufferedWriter?

FileWriter writes directly into Files and should be used only when the number of writes is less. BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better.

Which packages are used for Reading and Writing into files?

Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream classes).


1 Answers

you have not flushed the stream

public class Tp {
  public static void main(String[] args) throws IOException{
    File f = new File("/path/to/your/file/filename.txt");
    BufferedWriter bw = new BufferedWriter(new FileWriter(f));
    BufferedReader br = new BufferedReader(new  FileReader(f));
    bw.write("Some text");
    bw.flush();
    System.out.println(br.readLine());
    bw.write("Some more text");
    bw.flush();
    bw.close();
    br.close();
  }
}
like image 105
NuOne Avatar answered Nov 03 '22 07:11

NuOne