How do you get the text in system.output.println? [duplicate] - java

This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 8 years ago.
On the output part of my IDE (where all the system.out.println textx appear), I have several lines of text. I want to get them and save them to a text file. What would be the possible code for this?

use System#setOut() to redirect output to FileOutputStream to redirect System output to file
// for restore purpose
PrintStream oldOutStream = System.out;
PrintStream outFile = new PrintStream(
new FileOutputStream("/path/to/file.txt", true));
System.setOut(outFile);
System.out.println("this will goto file");
I assume you know about logging framework and you are not trying to use this for logging something

Yo can replce all sop with fileoutput strem and write everything in file
if you want to write log then you can use log4j
String content = "This is the content to write into file";
File file = new File("filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();

Related

Java how to add new line to file [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 2 years ago.
Im trying to add multiple strings to a file.
FileWriter myWriter = new FileWriter("cache.txt");
BufferedWriter bw=new BufferedWriter(myWriter);
bw.write(marker);
bw.newLine();
bw.close();
But whenever I write a new String it keeps overriding.
So I only have one string in my file.
How would I make it add a new line to the file.
Here is an example
What should happen.
file(cache.txt):
fd174d5b4bbc85295a649f9d70a4adf4
9b854017b04d62732ac00f2ee8007968
...
What happens for me
file(cache.txt):
9b854017b04d62732ac00f2ee8007968(last entry)
Because that's what BufferedWriter's .write is supposed to do.
If the file doesn't exists, create and write to it.
If the file exists, truncate (remove all content) and write to it
To append, use this:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("text");
out.close();
} catch (IOException e) {
//exception handling
}
Use the "append" flag to the FileWriter constructor:
FileWriter myWriter = new FileWriter("cache.txt", true);
Otherwise the file will be reset to the beginning each time it is opened.

Null pointer when reading a Properties file from another folder [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My application will check if a Properties file exists and create one if not.
try{
// create new file
String path="c:\\temp\\LaserController.properties";
File file = new File(path);
String comport = "Comport=COM1";
String Parity = "parity=none";
String baud = "baud=9600";
String Stopbits = "StopBits=0";
String databits = "DataBits=8";
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// write in file
bw.write(comport);
bw.newLine();
bw.write(Parity);
bw.newLine();
bw.write(baud);
bw.newLine();
bw.write(Stopbits);
bw.newLine();
bw.write(databits);
// close connection
bw.close();
}
But when i try to read the properties file like this i get a Null pointer.
else {
Properties prop = new Properties();
InputStream input = LaserControllerUI.class.getResourceAsStream("c:\\temp\\LaserController.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty(Comport+"comport"));
System.out.println(prop.getProperty("Parity"));
System.out.println(prop.getProperty("Baud"));
input.close();
}
}catch(Exception e){
System.out.println(e);
}
}
It fails on the InputStream input line but i dont know why. the file exists and my application can access it because it put it there in the first place. What am i doing wrong?
The file has to be in a location that is accessible to users to change parameters.
getResourceAsStream method needs a "class-path relative" name. You are providing an absolute path. Try to use FileInputStream instead.
E.g:
InputStream input = new FileInputStream("c:\\temp\\LaserController.properties");
I suggest using Properties.save() to ensure it is written in a format when can be read.
I suggest you look at the text file to see what was written.
BTW The properties are case sensitive. you write
Comport
parity
baud
but you read
Comport+"comport"
Parity
Baud
so they will all be null.
Move that file to resource folder or add that folder as resource folder
getClass().getClassLoader().getResourceAsStream("LaserController.properties")

JAVA write new row to .CSV file [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 6 years ago.
How can I write a new row of data to a .CSV file that already has data in it. So far my code just clears the file and doesn't actually write anything?
BufferedReader br = null;
BufferedWriter bw = null;
String fileString = "patients.csv";
String fileLine = "";
File file = new File(fileString);
br = new BufferedReader(new FileReader(file));
FileWriter fw = new FileWriter(fileString);
bw = new BufferedWriter(fw);
while((fileLine = br.readLine()) != null){
bw.write(fileLine);
}
br.close();
bw.close();
specify true in the constructor java FileWriter to know that the true and append be added to the end of the file if you place it does not overwrite information
FileWriter fw = new FileWriter(fileString,true);
If you want to append to a file using FileWriter then use this Constructor
As per Javadocs
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be written to the end of the file
rather than the beginning.
But, back to your code, you will only need to write new data to the FileWriter and not rewrite existing data.

Multiple Lines into One Text File? - Java

How can I save multiple lines into One Text File?
I want to print "New Line" in the same Text File every time the code is executed.
try {
FileWriter fw = new FileWriter("Test.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("New Line");
pw.close();
}
catch (IOException e)
{
System.out.println("Error!");
}
I'm able to create a new file but can't create a new line every time the code is executed.
Pass true as a second argument to FileWriter to turn on "append" mode.
FileWriter fw = new FileWriter("filename.txt", true);
That will make your file to open in the append mode, which means, your result will be appended to the end of the file each time you'll write to the file. You can also write '\n' after each content writing so that it will inserts a new line there.
You are creating a new line every time it is run, the problem is that you are truncating the file when you open it. I suggest you append to the file each time.
try (FileWriter fw = new FileWriter("Test.txt", true); // true for append
PrintWriter pw = new PrintWriter(fw)) {
pw.println("New Line");
} // try-with-resource closes everything.
Note: openning and closing a file for each line is expensive, If you do this a lot I suggest leaving the file open and flushing the output each time.
You are doing this:
FileWriter fw = new FileWriter("Test.txt");
which is overwriting the file every time you execute that line...
BUT you need instead to append the data to the file
FileWriter fw = new FileWriter("Test.txt", true);
take a look at the constructor in the doc
You need to open the file in append mode. You can do that as follows:
FileWriter fw = new FileWriter("Test.txt", true);
Here is the documentation for the same.

How to appened data to a file using BufferedWriter and FileOutPutStream [duplicate]

This question already has answers here:
How to write data with FileOutputStream without losing old data?
(2 answers)
Closed 8 years ago.
In the below code I am trying to append some text to a file using FileOutputStream and BufferedWriter as shown below.At ru time, despite the file has some data, when i use FileOutputStream and BufferedWriter i found the file is empty and even the data i want to append bw.write("new information"); is not existing the file is completely empty.
Kindly please let me know how to fix it.
Code:
File f = new File(SystemConfig.getSystConfigInstance("E"));
System.out.println(f.getAbsolutePath() + " name: " + f.getName());
OutputStream os = new FileOutputStream(f);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write("new information");
Try this, FileOutputStream(File file,
boolean append) with append
OutputStream os = new FileOutputStream(f, true);
If the append boolean is true which means it will append the new content with the old content.
instead of
OutputStream os = new FileOutputStream(f);
FileOutputStream has the default append method also. So use this to append the content with the old one.
File f = new File(SystemConfig.getSystConfigInstance("E"));;
System.out.println(f.getAbsolutePath() + " name: " + f.getName());
OutputStream os = new FileOutputStream(f,true);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write("new information");
bw.close();
You have missed append flag for FileOutputStream. Then only it created as appendable. Otherwise it will like a read only.
Next , end of the file you need to close the writer. So that only it will flush entire data.
Try this (please note the boolean passed to FileOutputStream):
File f = new File(SystemConfig.getSystConfigInstance("E"));
System.out.println(f.getAbsolutePath() + " name: " + f.getName());
OutputStream os = new FileOutputStream(f, true); // <--- append = true
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write("new information");
For more info read the official doc of FileOutputStream:
FileOutputStream(File file, boolean append)
If the second argument is true, then bytes will be written to the end
of the file rather than the beginning.

Categories

Resources