Java printwriter to string

[Solved]-how to convert PrintWriter to String or write to a File?-Java

It will depend on: how the PrintWriter is constructed and then used.

If the PrintWriter is constructed 1st and then passed to code that writes to it, you could use the Decorator pattern that allows you to create a sub-class of Writer, that takes the PrintWriter as a delegate, and forwards calls to the delegate, but also maintains a copy of the content that you can then archive.

public class DecoratedWriter extends Writer < private final Writer delegate; private final StringWriter archive = new StringWriter(); //pass in the original PrintWriter here public DecoratedWriter( Writer delegate ) < this.delegate = delegate; >public String getForArchive() < return this.archive.toString(); >public void write( char[] cbuf, int off, int len ) throws IOException < this.delegate.write( cbuf, off, len ); this.archive.write( cbuf, off, len ); >public void flush() throws IOException < this.delegate.flush(); this.archive.flush(); >public void close() throws IOException < this.delegate.close(); this.archive.close(); >> 

This helped me: for obtaining a SOAP-able object as XML string.

JAXBContext jc = JAXBContext.newInstance(o.getClass()); Marshaller m = jc.createMarshaller(); StringWriter writer = new StringWriter(); m.marshal( o, new PrintWriter(writer) ); return writer.toString(); 

The best way I think is prepare your response in other object like StringBuffer, and fush its content to the response, and after save the content stored in that variable to the file.

Along similar lines to what cdc is doing — you can extend PrintWriter and then create and pass around an instance of this new class.

Call getArchive() to get a copy of the data that’s passed through the writer.

public class ArchiveWriter extends PrintWriter < private StringBuilder data = new StringBuilder(); public ArchiveWriter(Writer out) < super(out); >public ArchiveWriter(Writer out, boolean autoFlush) < super(out, autoFlush); >public ArchiveWriter(OutputStream out) < super(out); >public ArchiveWriter(OutputStream out, boolean autoFlush) < super(out, autoFlush); >public ArchiveWriter(String fileName) throws FileNotFoundException < super(fileName); >public ArchiveWriter(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException < super(fileName, csn); >public ArchiveWriter(File file) throws FileNotFoundException < super(file); >public ArchiveWriter(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException < super(file, csn); >@Override public void write(char[] cbuf, int off, int len) < super.write(cbuf, off,len); data.append(cbuf, off, len); >@Override public void write(String s, int off, int len) < super.write(s, off,len); data.append(s, off, len); >public String getArchive() < return data.toString(); >> 

You cannot get it with just your PrintWriter object. It flushes the data, and does not hold any content within itself. This isn’t the object you should be looking at to get the entire string,

Navneeth G 7145

Why not use StringWriter instead? I think this should be able to provide what you need.

StringWriter strOut = new StringWriter(); . String output = strOut.toString(); System.out.println(output); 

Alvin Bunk 7391

Читайте также:  Webmail timeweb ru https webmail timeweb ru src auth php

To get a string from the output of a PrintWriter , you can pass a StringWriter to a PrintWriter via the constructor:

@Test public void writerTest() < StringWriter out = new StringWriter(); PrintWriter writer = new PrintWriter(out); // use writer, e.g.: writer.print("ABC"); writer.print("DEF"); writer.flush(); // flush is really optional here, as Writer calls the empty StringWriter.flush String result = out.toString(); assertEquals("ABCDEF", result); >

weston 52715

  • How to convert 8 character string into a single byte at a time to write to file in Java?
  • How to write String to txt file and send it to server
  • how to write the newline character as a string to a file java
  • How to convert String to a file Name
  • Write a string in a file exactly how it is
  • How can I convert a string in a file into an array?
  • how to read from excel file replace string in xml and write into new file java
  • How to write a String line to a file every-time I press the «Write» Button
  • In java, how to write an object to a file and later on read it from the file and convert it back to the original object in the HDFS?
  • How to send the xml file and xml string to jms queue?
  • How to convert a string to an EObject?
  • How can I write a server side java code to return any kind of file as stream using JAX-RS(Jersey)?
  • How do I read X and Y coordinates of a string in a File of type Word or Txt?
  • Write string with newlines to file
  • how to return a string value from an event handler to another file in same package java
  • How to write to file
  • How to have no bugs when multiple instances of a java applet write on the same file on a server
  • How do I count words from a file or string object using a nested for loop?
  • How to write to a compressed file in spring-batch
  • How to write specific log to txt file
  • how to write multiple video files together to create one video file
  • how do i convert xml file to file type in eclipse
  • How to convert .txt files to multiline String in Android Java
  • How to write data into Excel file in order
  • How to write multiple LinkLists in a file and read the LinkedLists into a ArrayList of LinkedList?
  • I am getting date as String from jsp page how to convert it in to java.util.Date
  • How to write packets from vpn tunnel to pcap file
  • How to write TXT file to sdcard?
  • how can I get list of network active connections ( pocess name, ID, PID, stat,TCp or UDP. )and write them to XML file in java
  • How to convert polymorphic json string to java bean class
Читайте также:  Работа с csv питон

More Query from same tag

  • Returning after a for loop
  • Function value always getting multiplied by 2
  • Taking a Textfield input converting to an int and then limiting the value
  • this as reference in Object assignment
  • @BeforeAll JUnit/spring-boot-test alternative that runs when application context starts
  • how to check if the url matchs the identifier?
  • java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
  • Can anyone tell me what I’m doing wrong? — Stacks
  • How to resize JScrollPane itself (not viewport) programmatically?
  • NestedScrollView not showing inside CoordinatorLayout
  • Reading data from a text file in Java
  • AADSTS50011 The reply address is not using a secure scheme[AZURE]
  • Android Animation bug
  • How to use Java stream map with filters and optional?
  • Defining variable and using switches
  • java.time.format.DateTimeParseException: Text ‘2016-08-30T06:18:17:698-0600’ could not be parsed at index 24
  • I am new to programming and need to store the below input in one array. Any suggestions?
  • Java ShutDownHook not being fired on Windows
  • Java automatically connect to server if it opened
  • Mediaplayer sound does not overlap
  • How to convert a JSON file to a readable object in Java
  • Why can I access a private instance variable without a getter method?
  • bounded stack implementation
  • Relationship between HttpClient, HttpConnection and ClientConnectionManager
  • onclick function in android button with animation is not working
  • Broker Already Created JMS
  • Handling of JOptionPane cancel button, which takes string as input
  • count no. of set bits of each number in a range and then sum it up
  • Can’t get groups to work
  • extract relevant subgraph of a resource

Источник

Java printwriter to string

Класс PrintStream

Класс PrintStream — это именно тот класс, который используется для вывода на консоль. Когда мы выводим на консоль некоторую информацию с помощью вызова System.out.println() , то тем самым мы задействует PrintStream , так как переменная out в классе System как раз и представляет объект класса PrintStream, а метод println() — это метод класса PrintStream.

Но PrintStream полезен не только для вывода на консоль. Мы можем использовать данный класс для записи информации в поток вывода. Для этого PrintStream определяет ряд конструкторов:

PrintStream(OutputStream outputStream) PrintStream(OutputStream outputStream, boolean autoFlushingOn) PrintStream(OutputStream outputStream, boolean autoFlushingOn, String charSet) throws UnsupportedEncodingException PrintStream(File outputFile) throws FileNotFoundException PrintStream(File outputFile, String charSet) throws FileNotFoundException, UnsupportedEncodingException PrintStream(String outputFileName) throws FileNotFoundException PrintStream(String outputFileName, String charSet) throws FileNotFoundException, UnsupportedEncodingException

Параметр outputStream — это объект OutputStream, в который производится запись. Параметр autoFlushingOn при значении true позволяет автоматически записывать данные в поток вывода. По умолчанию этот параметр равен false. Параметр charSet позволяет указать кодировку символов.

В качестве источника для записи данных вместо OutputStream можно использовать объект File или строковый путь, по которому будет создаваться файл.

Читайте также:  Index html root directory

Для вывода информации в выходной поток PrintStream использует следующие методы:

  • println() : вывод строковой информации с переводом строки
  • print() : вывод строковой информации без перевода строки
  • printf() : форматированный вывод

Например, запишем информацию в файл:

import java.io.*; public class Program < public static void main(String[] args) < String text = "Привет мир!"; // строка для записи try(FileOutputStream fos=new FileOutputStream("C://SomeDir//notes3.txt"); PrintStream printStream = new PrintStream(fos)) < printStream.println(text); System.out.println("Запись в файл произведена"); >catch(IOException ex) < System.out.println(ex.getMessage()); >> >

В данном случае применяется форма конструктора PrintStream, которая в качестве параметра принимает поток вывода: PrintStream (OutputStream out) . Кроме того, мы могли бы использовать ряд других форм конструктора, например, указывая названия файла для записи: PrintStream (string filename)

В качестве потока вывода используется объект FileOutputStream . С помощью метода println() производится запись информации в выходной поток — то есть в объект FileOutputStream. (В случае с выводом на консоль с помощью System.out.println() в качестве потока вывода выступает консоль)

Кроме того, как и любой поток вывода и наследник класса OutputStream он имеет метод write :

import java.io.*; public class Program < public static void main(String[] args) < try(PrintStream printStream = new PrintStream("notes3.txt")) < printStream.print("Hello World!"); printStream.println("Welcome to Java!"); printStream.printf("Name: %s Age: %d \n", "Tom", 34); String message = "PrintStream"; byte[] message_toBytes = message.getBytes(); printStream.write(message_toBytes); System.out.println("The file has been written"); >catch(IOException ex) < System.out.println(ex.getMessage()); >> >

После выполнения этой программы получится файл со следующим содержанием:

Hello World!Welcome to Java! Name: Tom Age: 34 PrintStream

PrintWriter

На PrintStream похож другой класс PrintWriter . Его можно использовать как для вывода информации на консоль, так и в файл или любой другой поток вывода. Данный класс имеет ряд конструкторов:

  • PrintWriter(File file) : автоматически добавляет информацию в указанный файл
  • PrintWriter(File file, String csn) : автоматически добавляет информацию в указанный файл с учетом кодировки csn
  • PrintWriter(OutputStream out) : для вывода информации используется существующий объект OutputStream, автоматически сбрасывая в него данные
  • PrintWriter(OutputStream out, boolean autoFlush) : для вывода информации используется существующий объект OutputStream, второй параметр указывает, надо ли автоматически добавлять в OutputStream данные
  • PrintWriter(String fileName) : автоматически добавляет информацию в файл по указанному имени
  • PrintWriter(String fileName, String csn) : автоматически добавляет информацию в файл по указанному имени, используя кодировку csn
  • PrintWriter(Writer out) : для вывода информации используется существующий объект Writer, в который автоматически идет запись данных
  • PrintWriter(Writer out, boolean autoFlush) : для вывода информации используется существующий объект Writer, второй параметр указывает, надо ли автоматически добавлять в Writer данные

PrintWriter реализует интерфейсы Appendable, Closable и Flushable, и поэтому после использования представляемый им поток надо закрывать.

Для записи данных в поток он также используется методы printf() и println() .

Например, применим данный класс для вывода на консоль:

try(PrintWriter pw = new PrintWriter(System.out))

В качестве потока вывода здесь применяется System.out, а на консоль будет выведена строка «Hello world!»

Источник

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