Editing an already existing text file - java

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.

Related

How to properly read and write files in Gradle resources?

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();

Appending a string on the specific place in txt file - Java

I'am trying to append string(link) to the txt file on the specific place(In line where is "Link:"), to get line in file like "Link: www.link.something". I am using next code but my logic doesn't work.
if(file.getName().equals(filename+".txt")) {
link = line;
BufferedReader br;
BufferedWriter bw;
boolean no=false;
String lineE;
String data="Link:";
String lessonPath=link;
br = new BufferedReader(new FileReader(file));
while((lineE =br.readLine()) !=null){
if(!no){
data=line;
no=true;
}else{
data = data+"\n"+lineE;
}
}
bw = new BufferedWriter(new FileWriter(file));
bw.write(data+"\n"+lessonPath);
System.out.println(data+lessonPath);
bw.flush();
bw.close();
br.close();
}
If you can modify the text file then you could use StringSubstitutor to replace the template.

Java program is not writing all the records to the output file using the BufferedWriter

This below code is not able to write more than 29499 lines in the output file. More over the last line was printed only half. I have verified there is no issue with the program as the program is print all the 25000 lines in console.
FileReader fr = new FileReader(System.getProperty("user.dir") + "/json/Sample.json");
FileWriter fw = new FileWriter(System.getProperty("user.dir") + "/json/output.json");
BufferedReader br = new BufferedReader(fr);
BufferedWriter bw = new BufferedWriter(fw);
String line=br.readLine();
if (line == null)
{
br.close();
fr.close();
bw.flush();
bw.close();
fw.close();
}
while (line!=null) {
Gson gson = new Gson();
bw.write(record+"\n");
line=br.readLine();
}
You only close and flush your readers & writers if the first line is null. You presumably instead want to do this after your loop completes, which will ensure that (exceptions aside) they'll always close.
Even better, use the try with resources statement to avoid having to close / flush them manually at all - this will also handle the case where an exception it thrown.

How can I make PrintWriter NOT append to a file?

I have a server that writes to a logfile, but I do not want to append lines. I have set the flag to false, but still it seems to be appending. How can I make it REPLACE the first line everytime so my file contains one updated line everytime ?
fos = new FileOutputStream(new File(filename), false);
PrintWriter bw = new PrintWriter(new OutputStreamWriter(fos));
..
..
while(true){
line = getRandomLine();
bw.println(line);
bw.flush();
}
..
..
If I understand You correctly, you want this:
File file = new File(filename);
while (true) {
pw = new PrintWriter(file);
line = getRandomLine();
pw.println(line);
pw.flush();
pw.close();
}

Good practice in Java File I/O

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)));

Categories