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)));
Related
Java Gradle project
File saving in build/resources, but reading from src/resources
Does anyone know how to save and read from the same directory?
below is my code for writing:
File file = new File((this.getClass().getClassLoader().getResource("test.txt")).toURI());
FileWriter fw = new FileWriter(file, false);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
pw.println("test");
pw.close();
below is my code for reading:
BufferedReader br = new BufferedReader(new FileReader(new File((this.getClass().getClassLoader().getResource("test.txt")).toURI())));
String amount = br.readLine();
I'm trying to edit an existing file that I had just created and so far I have no clue on how it's done.
Can anyone show me how and please explain line by line on what the code does?
import java.io.*;
public class Hey {
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Title");
String title = br.readLine();
File f = new File(title +".txt");
f.createNewFile();
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
System.out.println("What you want to input in the text");
String text = br.readLine();
bw.write(text);
bw.flush();
bw.close();
}
}
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
Creates a read buffer from the standard input.
String title = br.readLine();
Reads from this buffer until there's a return character sequence found ('\n', '\r' or "\r\n"). The entire line excluding the return sequence will be saved as title.
File f = new File(title +".txt");
Creates a File object with the name read from the console.
f.createNewFile();
Creates the file if it doesn't exist yet.
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
Creates a buffered writer to write into fw.
String text = br.readLine();
Again reads a line from the console.
bw.write(text);
Writes this line into the buffer.
bw.flush();
Ensures the whole buffer is flushed into the file (written into the file).
bw.close();
Closes the buffer of your buffered writer. You should also close the reader buffer br and the FileWriter fw.
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));
So what I'm trying to do is to copy information from file2 to the begin of file1. If someone could help me I would really appreciate your time, thank you.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
FileInputStream fileReader = new FileInputStream(reader.readLine()); //file1
FileOutputStream fileWriter = new FileOutputStream(reader.readLine(), true); //file2
while (fileReader.available() > 0) {
int data = fileReader.read();
fileWriter.write(data);
}
fileReader.close();
fileWriter.close();
reader.close();
File employe = new File("E:five/emplo.xml");
File stud = new File("E:/one/two/student.xml");
how to combine these two files in one file object
If you want to merge two standard text files then you can just use filewriters and filereaders.
I assuming that this is not some xml specific thing as I am not experienced with them.
Here is how to read a file (without the exception handling):
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr); // the only reason I use this is because I am used to line by line handling
String line;
while((line = br.readLine()) != null)
{
// do something with each line
}
You could read each file into an arraylist of strings then output using:
FileWriter fout = new FileWriter(file, toAppend);
fout.write(msg);
fout.close();
String[] filenames = new String[]{ "emplo.xml", "student.xml"};
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("merged.xml");
for (String filename : filenames) {
InputStream inputStream = new BufferedInputStream(new FileInputStream(filename);
org.apache.commons.io.IOUtils.copy(inputStream, outputStream);
inputStream.close();
}
outputStream.close();<br/>
or you can also use SAXParser