How to write console output to a txt file - java

I have tried to write the console output to a txt file using this code suggestion (http://www.daniweb.com/forums/thread23883.html#) however I was not successful. What's wrong?
try {
//create a buffered reader that connects to the console, we use it so we can read lines
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//read a line from the console
String lineFromInput = in.readLine();
//create an print writer for writing to a file
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//output to the file a line
out.println(lineFromInput);
//close the file (VERY IMPORTANT!)
out.close();
}
catch(IOException e1) {
System.out.println("Error during reading/writing");
}

You need to do something like this:
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
The second statement is the key. It changes the value of the supposedly "final" System.out attribute to be the supplied PrintStream value.
There are analogous methods (setIn and setErr) for changing the standard input and error streams; refer to the java.lang.System javadocs for details.
A more general version of the above is this:
PrintStream out = new PrintStream(
new FileOutputStream("output.txt", append), autoFlush);
System.setOut(out);
If append is true, the stream will append to an existing file instead of truncating it. If autoflush is true, the output buffer will be flushed whenever a byte array is written, one of the println methods is called, or a \n is written.
I'd just like to add that it is usually a better idea to use a logging subsystem like Log4j, Logback or the standard Java java.util.logging subsystem. These offer fine-grained logging control via runtime configuration files, support for rolling log files, feeds to system logging, and so on.
Alternatively, if you are not "logging" then consider the following:
With typical shells, you can redirecting standard output (or standard error) to a file on the command line; e.g.
$ java MyApp > output.txt
For more information, refer to a shell tutorial or manual entry.
You could change your application to use an out stream passed as a method parameter or via a singleton or dependency injection rather than writing to System.out.
Changing System.out may cause nasty surprises for other code in your JVM that is not expecting this to happen. (A properly designed Java library will avoid depending on System.out and System.err, but you could be unlucky.)

There is no need to write any code, just in cmd
on the console you can write:
javac myFile.java
java ClassName > a.txt
The output data is stored in the a.txt file.

to preserve the console output, that is, write to a file and also have it displayed on the console, you could use a class like:
public class TeePrintStream extends PrintStream {
private final PrintStream second;
public TeePrintStream(OutputStream main, PrintStream second) {
super(main);
this.second = second;
}
/**
* Closes the main stream.
* The second stream is just flushed but <b>not</b> closed.
* #see java.io.PrintStream#close()
*/
#Override
public void close() {
// just for documentation
super.close();
}
#Override
public void flush() {
super.flush();
second.flush();
}
#Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
second.write(buf, off, len);
}
#Override
public void write(int b) {
super.write(b);
second.write(b);
}
#Override
public void write(byte[] b) throws IOException {
super.write(b);
second.write(b);
}
}
and used as in:
FileOutputStream file = new FileOutputStream("test.txt");
TeePrintStream tee = new TeePrintStream(file, System.out);
System.setOut(tee);
(just an idea, not complete)

Create the following method:
public class Logger {
public static void log(String message) {
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
out.write(message);
out.close();
}
}
(I haven't included the proper IO handling in the above class, and it won't compile - do it yourself. Also consider configuring the file name. Note the "true" argument. This means the file will not be re-created each time you call the method)
Then instead of System.out.println(str) call Logger.log(str)
This manual approach is not preferable. Use a logging framework - slf4j, log4j, commons-logging, and many more

In addition to the several programatic approaches discussed, another option is to redirect standard output from the shell. Here are several Unix and DOS examples.

You can use System.setOut() at the start of your program to redirect all output via System.out to your own PrintStream.

This is my idea of what you are trying to do and it works fine:
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new FileWriter("c://output.txt"));
try {
String inputLine = null;
do {
inputLine=in.readLine();
out.write(inputLine);
out.newLine();
} while (!inputLine.equalsIgnoreCase("eof"));
System.out.print("Write Successful");
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}

The easiest way to write console output to text file is
//create a file first
PrintWriter outputfile = new PrintWriter(filename);
//replace your System.out.print("your output");
outputfile.print("your output");
outputfile.close();

To write console output to a txt file
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A TEXT FILE";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
FileWriter writer = null;
try {
writer = new FileWriter("final.txt");
writer.write(listString);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to generate the PDF rather then the text file, you use the dependency given below:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>
To generate a PDF, use this code:
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A PDF";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
Document document = new Document();
try {
PdfWriter writer1 = PdfWriter
.getInstance(
document,
new FileOutputStream(
"final_pdf.pdf"));
document.open();
document.add(new Paragraph(listString));
document.close();
writer1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}

PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("C:\\testing.txt"));
} catch (IOException e) {
e.printStackTrace();
}
out.println("output");
out.close();
I am using absolute path for the FileWriter. It is working for me like a charm. Also Make sure the file is present in the location. Else It will throw a FileNotFoundException. This method does not create a new file in the target location if the file is not found.

In netbeans, you can right click the mouse and then save as a .txt file. Then, based on the created .txt file, you can convert to the file in any format you want to get.

Related

Java : Writing CSV in String format to CSV in a file

A method returns a String in comma separated format. For example, the returned String can be like the one given below.
Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China
I will need to get this String and write it into a CSV file. I'll have to insert a header and a footer for this file as well.
For example, when I open the file, the contents for the above data will be
Name,Age,Gender,Country
Tarantino,50,M,USA
Carey Mulligan,27,F,UK
Gong Li,45,F,China
How do we do that ? Are there any open source libraries to do this task ?
CSV format is not very well defined. You don't have to write headers for the file. Instead it is pretty SIMPLE format. Data values are separated using commas or semicolon or space etc.
You just have to write your own simple method that writes your string to a file on local computer using FileOutputStream or Writer in java.io package.
You can use this as a learning example.
I used BufferedReader because he will take care about line separators, but you can also use #split method, and write the resulting tokens.
import java.io.*;
public class Tests {
public static void main(String[] args) {
File file = new File("out.csv");
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(file));
String string = "Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China";
BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(string.getBytes())));
String line;
while ((line = reader.readLine()) != null) {
out.write(line.trim());
out.newLine();
}
}
catch (IOException e) {
// log something
e.printStackTrace();
}
finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignored
}
}
}
}
}
This is pretty simple
String str = "Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China";
PrintWriter pr = new PrintWriter(new FileWriter(new File("test.csv"), true));
String arr[] = str.split("\\n");
// splited the string by new line provided with the string
pr.println("Name,Age,Gender,Country");
// header written first and rest of data appended
for(String s : arr){
pr.println(s);
}
pr.close();
don't forget to close the stream in finally block and handle the exception

What is the simplest way to write a text file in Java?

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D
I searched the web and found this code, but I understand 50% of it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.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();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With Java 7 and up, a one liner using Files:
String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
You could do this by using JAVA 7 new File API.
code sample:
`
public class FileWriter7 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
writeSmallTextFile(lines, filepath);
}
private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aLines, StandardCharsets.UTF_8);
}
}
`
You can use FileUtils from Apache Commons:
import org.apache.commons.io.FileUtils;
final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);
Appending the file FileWriter(String fileName,
boolean append)
try { // this is for monitoring runtime Exception within the block
String content = "This is the content to write into file"; // content to write into the file
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here
// if file doesnt exists, then create it
if (!file.exists()) { // checks whether the file is Exist or not
file.createNewFile(); // here if file not exist new file created
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
bw.write(content); // write method is used to write the given content into the file
bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
System.out.println("Done");
} catch (IOException e) { // if any exception occurs it will catch
e.printStackTrace();
}
Your code is the simplest. But, i always try to optimize the code further. Here is a sample.
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
bw.write("Hello, This is a test message");
bw.close();
}catch (FileNotFoundException ex) {
System.out.println(ex.toString());
}
Files.write() the simple solution as #Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.
So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. :)
List<String> lines = Arrays.asList(new String[] { "line1", "line2" });
Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write(lines.stream()
.reduce((sum,currLine) -> sum + "\n" + currLine)
.get());
}
In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.
String content = "your content here";
Path path = Paths.get("/data/output.txt");
if(!Files.exists(path)){
Files.createFile(path);
}
BufferedWriter writer = Files.newBufferedWriter(path);
writer.write(content);
In Java 11 or Later, writeString can be used from java.nio.file.Files,
String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content);
With Options:
Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)
More documentation about the java.nio.file.Files and StandardOpenOption
File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));
IOUtils also can be used to write/read files easily with java 8.

How to read a certain line with a BufferedWriter

I am working on a simple save system for my game, which involves three methods, init load and save.
This is my first time trying out reading and writing to/from a file, so I am not sure if I am doing this correctly, therefore I request assistance.
I want to do this:
When the game starts, init is called. If the file saves does not exist, it is created, if it does, load is called.
Later on in the game, save will be called, and variables will be written to the file, line by line (I am using two in this example.)
However, I am stuck on the load function. I have no idea what do past the point I am on. Which is why I am asking, if it is possible to select a certain line from a file, and change the variable to that specific line.
Here is my code, like I said, I have no idea if I am doing this correctly, so help is appreciated.
private File saves = new File("saves.txt");
private void init(){
PrintWriter pw = null;
if(!saves.exists()){
try {
pw = new PrintWriter(new File("saves.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else{
try {
load();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void save(){
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream(new File("saves.txt"), true));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
pw.println(player.coinBank);
pw.println(player.ammo);
pw.close();
}
public void load() throws IOException{
BufferedReader br = new BufferedReader(new FileReader(saves));
String line;
while ((line = br.readLine()) != null) {
}
}
I was thinking of maybe having an array, parsing the string from the text file into a integer, putting it into the array, and then have the variables equal the values from the array.
Seems like your file is a key=value structure, I suggest you'll use Properties object in java.
Here's a good example.
Your file will look like this:
player.coinBank=123
player.ammo=456
To save:
Properties prop = new Properties();
prop.setProperty("player.coinBank", player.getCoinBank());
prop.setProperty("player.ammo", player.getAmmo());
//save properties to project root folder
prop.store(new FileOutputStream("player.properties"), null);
Then you'll load it like this:
Properties prop = new Properties();
prop.load(new FileInputStream("player.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("player.coinBank"));
System.out.println(prop.getProperty("player.ammo"));
Reading and writing are pretty much symmetric.
You're writing player.coinBank as the first line of the file, and player.ammo as the second line. So, when reading, you should read the first line and assign it to player.coinBank, then read the second line and assign it to player.ammo:
public void load() throws IOException{
try (BufferedReader br = new BufferedReader(new FileReader(saves))) {
player.coinBank = br.readLine();
player.ammo = br.readLine();
}
}
Note the use of the try-with-resources statement here, which makes sure the reader is closed, whatever happens in the method. You should also use this construct when writing to the file.

File write/read function like in PHP

So I'm learning new things day by day in Java, and I hope one day I should have same knowledge in Java as in PHP.
I'm trying to make a class that is similar to fopen, fwrite, fclose in PHP like:
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
I also need the method of writing
o - for delete and write/overwrite
a - for append at end
and a read function that returns the the content line by line, so I can put it into an array , like file_get_contents(file);
This is what I have so far ...
import java.io.*;
import java.util.Scanner;
/**
Read and write a file using an explicit encoding.
Removing the encoding from this code will simply cause the
system's default encoding to be used instead.
**/
public final class readwrite_txt
{
/** Requires two arguments - the file name, and the encoding to use. **/
public static void main(String[] args) throws IOException
{
String fileName = "text.txt";
String encoding = "UTF-8";
readwrite_txt test = new readwrite_txt(fileName,encoding);
test.write("argument.txt","some text","UTF-8","o");
}
/** Constructor. **/
readwrite_txt(String fileName, String encoding)
{
String fEncoding = "text.txt";
String fFileName = "UTF-8";
}
/** Write fixed content to the given file. **/
public void write(String fileName,String input,String encoding,String writeMethod) throws IOException
{
// Method overwrite
if(writeMethod == "o")
{
log("Writing to file named " + fileName + ". Encoding: " + encoding);
Writer out = new OutputStreamWriter(new FileOutputStream(fileName), encoding);
try
{
out.write(input);
}
finally
{
out.close();
}
}
}
/** Read the contents of the given file. **/
public void read(String fileName,String output,String encoding,String outputMethod) throws IOException
{
log("Reading from file.");
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new FileInputStream(fileName), encoding);
try
{
while (scanner.hasNextLine())
{
text.append(scanner.nextLine() + NL);
}
}
finally
{
scanner.close();
}
log("Text read in: " + text);
}
// Why write System.out... when you can make a function like log("message"); simple!
private void log(String aMessage)
{
System.out.println(aMessage);
}
}
also, I don't understand why I must have
readwrite_txt test = new readwrite_txt(fileName,encoding);
instead of
readwrite_txt test = new readwrite_txt();
I just want to have an simple function similar to that in PHP.
EDITED
So my function must be
$fp = fopen('data.txt', 'w'); ==> readwrite_txt test = new readwrite_txt(filename,encoding,writeMethod);
fwrite($fp, '23'); ==> test.write("the text");
fclose($fp); ==> ???
to read a file in java you can
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) //Start of reading file
{
//what you want to do with every line is here
}
but for readwrite_txt test = new readwrite_txt(); problem ..
you must have another constructor inside the class that doesn't take any parameters
Have a look at the following file handling tutorials (Google is littered with them):
http://www.javapractices.com/topic/TopicAction.do?Id=42
http://www.coderanch.com/t/403914/java/java/do-read-entire-file-all
Pay attention to the following classes:
FileInputStream
FileOutpuStream
Scanner
There's all sorts of examples out there for you to learn from.
You can use the BufferedReader, here is an example and BufferedWriter, here is an example of write and here is an example for appending. For reading line-by-line you can use the readLine method of BufferedReader. You don't need those parameters in your constructor, because you don't use them, but you don't even need a class to implement these features because there are already standard classes for this purpose.
I hope this helps.

Writing from System.out.println to a file

I've replaced many strings and outputted the result and now am trying to write those lines into a text file. Here's what I did. I created a new file:
File newfile = new File("/Users/Bill/Desktop/newfile.txt");
if (newfile.exists()) {
System.out.println("File exists");
} else {
newfile.createNewFile();
System.out.println("New file created");
}
And then I tried to write to the created file the result of System.out.println(lines[i]);
try {
WriteToFile newFile = new WriteToFile(newfile, true);
newFile.write(lines[i]);
// lines[i] is what I used to print out System.out.println(lines[i])
}
catch (IOException e) {
System.out.println("Error.");
}
I'm not getting what I'm expecting, though. Any suggestions?
WRITETOFILE:
public class WriteToFile {
private String path;
private boolean append = false;
public WriteToFile(String filename) {
path=filename;
}
public WriteToFile(String filename, boolean appendfile){
path=filename;
append=appendfile;
}
public void write(String text) throws IOException {
FileWriter filewrite = new FileWriter(path, append);
PrintWriter print = new PrintWriter(filewrite);
print.printf("%s" + "%n", text);
print.close();
}
}
Every time you call WriteToFile.write, it reopens the file for writing, truncating the file's original contents. You should open the file once, in the constructor (and store the PrintWriter in a field), and add a close method that calls close for the PrintWriter.
On the calling side, do this:
WriteToFile writer = new WriteToFile(filename);
try {
// writer.write(...);
} finally {
writer.close();
}
By having the close call in a finally block, you ensure the file is closed even if an exception causes the function to quit early.
Look at the 2nd argument of the FileWriter constructor in your code.
FileWriter filewrite = new FileWriter(path, append);
See, it says "append". Guess what it does. Read the documentation if you're unsure.
Now, look how you initialized append.
private boolean append = false;
This code is fully behaving as expected. It's just a developer's fault. Fix it :)
Just set fileName on System using the method
System.setOut(fileName);
Then whenever we want to print using System.out.println() it will directly print to the fileName you mention.

Categories