The code says:
PrintWriter write = new PrintWriter("newFile.txt");
write.println("TransformersLegends");
What is the best way to read from the file? I can't use File or Buffered Reader as it takes a file object and here I'm trying with a string.
What is the best way to read from the file?
You can use BufferedReader this way :
final String PATH = "newFile.txt";
BufferedReader br = new BufferedReader(new FileReader(PATH));
Just decorate the new FileReader with a new BufferedReader.
You can use a FileReader.
It have a constructor new FileReader(String path).
As said in commentary, a BufferedReader will be more efficient, you can instantiate it with a string too new BufferedReader(new FileReader("FILE_PATH"))
Related
I've just created a file in MainActivity using the code:
FileOutputStream outputStream = openFileOutput("user", Context.MODE_PRIVATE);
outputStream.close();
Now what to use if I want to read the file (noting that the file will be obviously created in the internal storage)?
And is there a way that makes the file reading works as the Scanner function in Java (where the string is being read word by word and line by line)?
Use openFileInput() with the same parameters as openFileOutput().
This is your solution what I understood from your question,
FileInputStream fIn = new FileInputStream(new File("FILE_PATH"));
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fIn));
String str = bufferedReader.readLine();
Hypothetically we have this line
BufferedReader inStream = new BufferedReader(new FileReader("src.txt"));
At opening and closure of file how to calculate its size (for example with length())
inStream.legth() ? at a System.out.println()?
Use the length method of the File class:
File f = new File(fileName);
System.out.println(f.length())
Please note that you can use the f in your BufferReader object too :
BufferedReader br = new BufferedReader(new FileReader(f));
Is it possible to use BufferedReader to read from a text file, and then while buffered reader is reading, at the same time it also storing the lines it read to another txt file using PrintWriter?
If you use Java 7 and want to copy one file directly into another, it is as simple as:
final Path src = Paths.get(...);
final Path dst = Paths.get(...);
Files.copy(src, dst);
If you want to read line by line and write again, grab src and dst the same way as above, then do:
final BufferedReader reader;
final BufferedWriter writer;
String line;
try (
reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
writer = Files.newBufferedWriter(dst, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
doSomethingWith(line);
writer.write(line);
// must do this: .readLine() will have stripped line endings
writer.newLine();
}
}
To directly answer your question:
you can, and you can also use BufferedWriter to do so.
BufferedReader br = new BufferedReader(new FileReader(new File("Filepath")));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Filepath")));
String l;
while((l=br.readLine())!=null){
... do stuff ...
bw.write("what you did");
}
bw.close();
If you just need to copy without inspecting the data, then it's a one liner:
IOUtils.copy(reader, printWriter);
Yes. Open the BufferedReader, and then create a PrintWriter. You can read from the stream as you write to the writer.
I am trying to read integers from a file, apply some operation on them and writing those resulting integers to another file.
// Input
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
Scanner s = new Scanner(br);
// Output
FileWriter fw = new FileWriter("out.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
int i;
while(s.hasNextInt())
{
i = s.nextInt();
pw.println(i+5);
}
I want to ask is it a good practice to wrap these input and output streams like this?
I am new to java and on internet, I saw lots of other ways of I/O in files. I want to stick to one approach so is above the best approach ?
- Well consider that you went shopping into a food mall, Now what you do usually, pick-up each item from the selves and then go to the billing counter then again go to the selves and back to billing counter ....?? Or Store all the item into a Cart then go to the billing counter.
- Its similar here in Java, Files deal with bytes, and Buffer deals with characters, so there is a conversion of bytes to characters and trust me it works well, there will not be any noticeable overhead.
So to Read the File:
File f = new File("Path");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
So to Write the File:
File f = new File("Path");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
And when you use Scanner there is no need to use BufferedReader
Keep in mind that the design of those classes is based on the Decorator design pattern. A good practice is to close all instances of java.io.Closeable in a finally block. For example:
Reader r = null;
Scanner s = null;
try {
r = new FileReader("test.txt");
s = new Scanner(r);
// Do your stuff here.
} finally {
if (r != null)
r.close();
if (s != null)
s.close();
}
or, if you are using Java 7 or higher:
try (
Reader r = new FileReader("test.txt");
Scanner s = new Scanner(r)
) {
// Do your stuff here.
}
you dont really need BuffredWriter when you are using PrintWriter to write character data, printwriter has a constructor which takes filewriter as an argument. and dont need a scanner to read from a file you could acheive it using bufferedreader itself.
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
while((line=br.readLine())!=null){
//do read operations here
}
FileWriter fw = new FileWriter("out.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("write some data to the file")
Scanner does not need the BufferedReader. You can wrap it over the FileReader.
Scanner s = new Scanner(new FileReader("test.txt"));
While using the scanner its better to assume that the source contains various content. Its good to close the scanner after using it.
while(s.hasNext()){
if(s.hasNextInt())
int i = s.nextInt();
s.next();
}
s.close();
I usually do this:
String inputFileLocation = "Write it here";
BufferedReader br = new BufferedReader(new FileReader(new File(fileLocation)));
while((line=br.readLine())!=null){
//Scanner operations here
}
String outputFileLocation = "Here";
PrintWriter pr = new PrintWriter(new FileWriter(new File(outputFileLocation)));
I have 2 classes who must read an InputStream, the first one should only interpret the first line of the stream BUT the first line should be removed from the stream so that class B can interpret everything after the first line. Which doesn't work when I pass my InputStream to a BufferedReader and do a readLine().
I know I could do a read on the stream until I've encountered a \b but maybe a more proper solution exists to do the job?
// Reads the first line from the stream and everything else
public String retrieveFileNameFromTheFirstLineInInputStream(InputStream in) throws IOException {
InputStreamReader isReader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(isReader);
return reader.readLine();
}
You can't remove something from an InputStream, you just can read from it. Don't use the BufferedReader to read the line, because it surely will read much more than the first line from the InputStreamReader (to fill its buffer) which itself reads from the InputStream.
I'd suggest to read using the InputStreamReader until the end of the line is reached, then pass the InputStream instance to your code which should read it.
BTW, you always should specify the encoding used by the InputStreamReader, otherwise the system encoding will be used to convert the bytes from the InputStream to characters which can differ on different machines.
I believe even InputStreamReader can buffer input, so Mike L's answer can miss input.
It's awkward, but you could use ReaderInputStream from Apache commons-io. So:
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String firstLine = reader.readLine();
InputStream in2 = new ReaderInputStream(reader);
// continue with in2 ..