Java error stream to file

How To Write Console Output To Text File In Java

The java.lang.System‘s out and err objects are used to write text data to the standard output stream and standard error stream. The default output stream is the command-line console. But the java.lang.System class also provides a method for you to redirect the standard output stream to other destinations such as file stream. With this, you can log text data to a log file in your java program.

1. Redirect Java System Output Stream Methods.

  1. The java.lang.System class provides the below methods to set standard output stream to custom stream.
  2. setOut(PrintStream ps): Set standard data output to a specified print stream such as a file stream.
  3. setErr(PrintStream ps): Set standard error output to a specified print stream such as a file stream.
  4. setIn(InputStream is): Set standard input stream to a custom input stream.

2. Redirect Java Out Error Stream Examples.

  1. Below are the steps of redirecting the output stream to the file stream.
  2. Create a file output print stream.
PrintStream fileOut = new PrintStream("./out.txt");
System.out.println("Email " + line + " is valid. Please input another one.");

3. Write Console Output To Text File In Java Examples.

package com.dev2qa.java.basic; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Scanner; public class OutputStreamRedirect < public static void main(String[] args) < try < // Save original out stream. PrintStream originalOut = System.out; // Save original err stream. PrintStream originalErr = System.err; // Create a new file output stream. PrintStream fileOut = new PrintStream("./out.txt"); // Create a new file error stream. PrintStream fileErr = new PrintStream("./err.txt"); // Redirect standard out to file. System.setOut(fileOut); // Redirect standard err to file. System.setErr(fileErr); // Wrapped Scanner to get user input. Scanner scanner = new Scanner(System.in); // Print data in command console. originalOut.println("Please input your email. "); // Read string line. String line = scanner.nextLine(); while(true) < // If user input 'quit' then break the loop. if("quit".equalsIgnoreCase(line)) < break; >if(!isValidEmail(line)) < // If user input is not a valid email then write log data to ./err.txt file and console. originalErr.println("Email " + line + " is not a valid email. Please input again."); System.err.println("Email " + line + " is not a valid email. "); >else < // If user input a valid email then write the email to ./out.txt and console. originalOut.println("Email " + line + " is valid. Please input another one."); System.out.println("Email " + line + " is valid. Please input another one."); >// Get next user input line text. line = scanner.nextLine(); > originalOut.println("Program exit. "); System.out.println("Program exit. "); // Do not forget set original output and error stream back again. System.setOut(originalOut); System.setErr(originalErr); >catch(FileNotFoundException ex) < ex.printStackTrace(); >> /* Check whether the string is an email address or not. */ private static boolean isValidEmail(String email) < boolean ret = true; if(email==null || email.trim().length()==0) < ret = false; >else < int index = email.indexOf("@"); if(index == -1) < ret = false; >> return ret; > >
package com.dev2qa.java.basic; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class OutputStreamRedirect < public static void main(String[] args) < try < // Create an instance of InputStreamReader class, it is used to read user input from command line console. InputStreamReader isr = new InputStreamReader(System.in); // Create an instance of OutputStreamWriter class, it is used to write text to command line console. OutputStreamWriter osw = new OutputStreamWriter(System.out); // Create a BufferedReader object and use this object to connect to the system.in(command line console) to get user input text. BufferedReader br = new BufferedReader(isr); // Create a BufferedWriter object to write text to system.out. BufferedWriter bw = new BufferedWriter(osw); bw.write("Please input a valid email address.\r\n"); bw.flush(); // Get user input text line from the command line console. String line = br.readLine(); if(isValidEmail(line)) < // If user input valid email address. String text = line + " is a valid email address.\r\n"; // Print the text to system.out command line console. bw.write(text); bw.flush(); // Print the user input email address to a text file. FileWriter fw = new FileWriter("out.txt"); PrintWriter pw = new PrintWriter(fw); pw.println(text); // Do not forget close the above writers to close the file pointer. pw.close(); >else < // If user input invalid email address. String text = line + " is not a valid email address.\r\n"; // Print the error text to system.out command line console. bw.write(text); bw.flush(); // Print the error text to an err.txt file. FileWriter fw = new FileWriter("err.txt"); PrintWriter pw = new PrintWriter(fw); pw.println(text); // Close the above writer object to close the file. pw.close(); >>catch(IOException e1) < System.out.println("Error during reading/writing"); >> /* Check whether the string is an email address or not. */ private static boolean isValidEmail(String email) < boolean ret = true; if(email==null || email.trim().length()==0) < ret = false; >else < int index = email.indexOf("@"); if(index == -1) < ret = false; >> return ret; > >

4. Why My Java Code Can Not Write Console Output To A Local Log Text File.

4.1 Question.

  1. I am new to java programming. And my java program generates a lot of log output text on the console screen using the method system.out.println() (2022/05/24).
  2. I want to save the above log text output to a log file instead of printing them on the console.
  3. Below is an example java source code, but it does not work as expected when I run it. Can anyone give me some suggestions? Thanks a lot.
Читайте также:  Свойства фона цвет css

4.2 Answer1.

  1. If you want to print the system standard output from the default console screen to a special file, you should change your java source code as below.
// Create an instance of the PrintWriter class to print text to FileWriter object. PrintWriter pw = new PrintWriter(fw); // Set the PrintWriter object to the system standard output. System.setOut(pw);
bool append = true; bool autoFlush = true; // Create the FileOutputStream object in append mode. FileOutputStream fos = new FileOutputStream("log.txt", append) // Create the PrintStream object with auto flush, then when the system.out.println() method is called the text will be flushed to the log.txt file immediately. PrintStream ps = new PrintStream(fos, autoFlush); // Set the PrintStream object to the syste.output. System.setOut(ps);

Источник

FileOutputStream: Stream closed

Solved, In short: the problem was that I wrote to an already closed FileOutputStream I noticed some strange semantics using the FileOutputStream class. If I create a FileOutputStream using this code:

try < File astDumpFile = new File(dumpASTPath); if(!astDumpFile.exists()) < astDumpFile.createNewFile(); >astDumpStream = new FileOutputStream(dumpASTPath); > catch( IOException e ) < dumpAST = false; //throw new IOException("Failed to open file for dumping AST: " + dumpASTPath); System.out.println("Failed to open file for dumping AST: " + dumpASTPath); >

at the beginning of the program ( astDumpStream is a member variable). Then if I later (~3 seconds later) write string data to the file, i get an IOException: stream closed :

However if I copy the excact code which I use to create the FileOutputStream to directly before writing to it, it works as expected. Now I wonder why do I get that exception if I create that object earlier, but not if I create it directly before I use it. EDIT: The exception:

java.io.IOException: Stream Closed at java.io.FileOutputStream.writeBytes(Native Method) at java.io.FileOutputStream.write(FileOutputStream.java:305) at MyClass.function(MyClass.java:208) 

I just noticed, that even though I get an exception, still some data was written to the file. Interrestingly the first line is written completely, then all following lines except the last line are missing. If I replace the written String dotGraph with something shorter everything is written correctly, however I still get that exception. EDIT: Environment Information:

[~]> lsb_release -a Distributor ID: Debian Description: Debian GNU/Linux testing (wheezy) Release: testing Codename: wheezy [~]> java -version java version "1.7.0_09" Java(TM) SE Runtime Environment (build 1.7.0_09-b05) Java HotSpot(TM) 64-Bit Server VM (build 23.5-b02, mixed mode) 

Источник

Читайте также:  Paragraph spacing figma css

java Stream closed exception occurs during File Writer write method

The code which I currently have as below used to write the response and recently i am getting java.io.IOException: Stream closed error frequently even though I closed the File Writer properly not sure why any body please help me on this.

Exception: Caused by: java.io.IOException: Stream closed at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:26) at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:99) at java.io.OutputStreamWriter.write(OutputStreamWriter.java:190) at com.test.resp.RespWriter.write(RespWriter.java:150) at com.ctc.wstx.sw.BufferingXmlWriter.flushBuffer(BufferingXmlWriter.java:1103) at com.ctc.wstx.sw.BufferingXmlWriter.flush(BufferingXmlWriter.java:213) at com.ctc.wstx.sw.BufferingXmlWriter.close(BufferingXmlWriter.java:194) at com.ctc.wstx.sw.BaseStreamWriter.finishDocument(BaseStreamWriter.java:1690) 

The place I am getting the exception at below place fileWriter.write(buff, off, len); Here is the place I am getting Exception

public void write(char[] buff, int off, int len) throws IOException < printWriter.write(buff, off, len); if(count < FILE_SIZE) < fileWriter.write(buff, off, len); Here is the place I am getting Exception count+=len; >> 
public RespWriter(RequestHeader header, PrintWriter printWriter) throws InitializationException < isClosed = false; if(StringUtil.isEmpty(FILE_PATH) || printWriter == null) < throw new InitializationException( InitializationException.ERR_CODE); >else < this.header = header; File responseFolder = new File(FILE_PATH.concat( "/".concat(header.getUserId()))); boolean dirCreated = responseFolder.mkdir(); if(responseFolder.exists() && responseFolder.isDirectory()) < responseFile = new File(responseFolder, "R"+header.getId()+FILE_EXTENSION); >else < throw new InitializationException( InitializationException.ERR_CODE, "response folder does not exist"); >this.printWriter = printWriter; try < fileWriter = new FileWriter(responseFile); >catch (IOException e) < log.error("FileWriter could not be created", e); >writeHeaderToFile(); > > private void writeHeaderToFile() < String headerStr = "\nRequest Header:\nnull\n"; try < if(header!=null) < headerStr="\n"+Thread.currentThread().getName() +" Request Header:\n" + header.toString() + "\n"; >fileWriter.write(headerStr, 0, headerStr.length()); fileWriter.write("Date:"); fileWriter.write(new Date().toString()+"\n"); fileWriter.write("Response:\n"+Thread.currentThread().getName()+": "); fileWriter.flush(); > catch (IOException e) < log.error("IOException occurred writing header to file", e); >> @Override public void close() throws IOException < if(!isClosed) < try < if(fileWriter!=null) < try < fileWriter.close(); >catch(IOException e) < log.error("IOException", e); >> if(printWriter!=null) < try < printWriter.close(); >catch(IOException e) < log.error("IOException", e); >> > finally < isClosed = true; >> > public void flush() throws IOException < if(printWriter!=null) < try < printWriter.flush(); >catch(IOException e) < log.error("IOException", e); >> if(fileWriter!=null) < try < fileWriter.flush(); >catch(IOException e) < log.error("IOException", e); >> > 

Any thing i missed in the code or do I want to create new FileWriter instance in the Write method. Please help on this. Thanks in Advance

Источник

Getting Stream closed when reading/writing to file Java

I’m implementing a small tool in Java. I have a excel document and from every sheet I need to generate a .sql file. I’ve created an sql file model, which I have to read from for every excel sheet then replace a value and write it back to another .sql file. The problem is I use a for where I loop through my sheets and for every sheet I need to read that sql file, modify it and export it somewhere else. I get a «Stream closed» error, and I don’t know how to close my buffer and/or my InputStream properly. Can you guys help me out with this ? This is my code: This gets everything from the file and converts it to a String

public String getString(InputStream is) throws IOException < BufferedReader reader = null; StringBuilder sb = new StringBuilder(); String line; try < reader = new BufferedReader(new InputStreamReader(is)); while ((line = reader.readLine()) != null) < sb.append(line + System.lineSeparator()); >> catch (IOException ex) < ex.printStackTrace(); >return sb.toString(); > 
public void exportFile(String text, String path, String name, String extension) < BufferedWriter output = null; try < File sqlFile = new File(path + name + extension); output = new BufferedWriter(new FileWriter(sqlFile)); output.write(text); >catch (IOException e) < e.printStackTrace(); logger.severe("Unable to write to file!\n"); >finally < if (output != null) < try < output.close(); >catch (IOException e) < e.printStackTrace(); logger.severe("Unable to close buffer\n"); >> > > 
 ClassLoader loader = this.getClass().getClassLoader(); InputStream createTableInputStream = loader.getResourceAsStream("val_table_create.sql"); if (createTableInputStream == null) < logger.severe("No tempalte found for creating table!\n"); return; >List bookSheets = getSheets(book); for (Sheet sheet : bookSheets) < setHeader(table, sheet); String exportText = getString(createTableInputStream); exportText = exportText.replaceAll(TABLE_NAME, tableName); // exportText = exportText.replaceAll(VAL_DATA_TYPE, valDataType); // exportText = exportText.replaceAll(MSG_TEXT_DATA_TYPE, messageDataType); exportFile(exportText, absoluteWorkspacePath + File.separator + outputPath + File.separator, tableName, ".sql"); >if (createTableInputStream != null)

Источник

Writing file: IOException: Stream closed

I’m having trouble figuring out why I’m getting the above error with my code. I create a new instance of both FileWriter and BufferedWriter each time the method is called, yet apparently the stream is already closed.

public static void addSpawn(Location spawn) < File spawns = new File("spawns.dat"); FileWriter write = null; BufferedWriter out = null; try < write = new FileWriter(spawns, true); out = new BufferedWriter(write); out.write(locToStr(spawn)); out.newLine(); >catch(Exception e) < System.out.println("Error writing spawn file: " + e.getMessage()); >finally < if(write != null) < try < write.close(); >catch(Exception e) < e.printStackTrace(); >> if(out != null) < try < out.close(); >catch(Exception e) < e.printStackTrace(); >> > > 

Please show the full stack trace, including an indication of which line in the code you’ve posted is throwing an exception.

1 Answer 1

BufferedWriter wraps a target Writer . When you close() it, it attempts to flush the underlying target Writer before closing it.

In your code, you invoke close() on the target FileWriter before invoking close on the BufferedWriter . When the BufferedWriter#close() tries to invoke flush on the FileWriter , that FileWriter is already closed and thus throws an exception.

You’ll want to close BufferedWriter first. Better yet, use a try-with-resources

try (FileWriter write = new FileWriter(spawns, true); BufferedWriter out = new BufferedWriter(write);)  

Источник

Оцените статью