Java - Possible to pipe PrintWriter to InputStream/Reader? - java

I want to pipe JSP PrintWriter out to another support class that takes InputStream or Writer as argument. I wonder if it's possible to simplify the process.
Of course I can write the output to a file, then use InputStream to read that file.

The "other" end of the JSP-provided PrintWriter is connected to the client (through the network, of course). You could create a new PrintWriter, pipe that to the support class and have the support class' output written to the original JSP PrintWriter.

Related

ObjectInputStream invalid stream header

When I'm using this shipet:
InputStream fs=new FileInputStream("some_file.txt");
ObjectInputStream is=new ObjectInputStream(fs);
the Java shows error:
>java.io.StreamCorruptedException: invalid stream header: 3130300A
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:857)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349)
FileInputStream works fine. DataInputStream works too.
The code runs in main method, and there are not any another code. I used another file, for example pom.xml, the error remained the same.
I can use DataInputStream instead of ObjectInputStream, but I don't understand the cause of such behavior.
You cannot read a text file with an ObjectInputStream. You can only write data created with an ObjectOutputStream, or some other device that follows the same format protocol.

equivalent to Files.readAllLines() for InputStream or Reader?

I have a file that I've been reading into a List via the following method:
List<String> doc = java.nio.file.Files.readAllLines(new File("/path/to/src/resources/citylist.csv").toPath(), StandardCharsets.UTF_8);
Is there any nice (single-line) Java 7/8/nio2 way to pull off the same feat with a file that's inside an executable Jar (and presumably, has to be read with an InputStream)? Perhaps a way to open an InputStream via the classloader, then somehow coerce/transform/wrap it into a Path object? Or some new subclass of InputStream or Reader that contains an equivalent to File.readAllLines(...)?
I know I could do it the traditional way in a half page of code, or via some external library... but before I do, I want to make sure that recent releases of Java can't already do it "out of the box".
An InputStream represents a stream of bytes. Those bytes don't necessarily form (text) content that can be read line by line.
If you know that the InputStream can be interpreted as text, you can wrap it in a InputStreamReader and use BufferedReader#lines() to consume it line by line.
try (InputStream resource = Example.class.getResourceAsStream("resource")) {
List<String> doc =
new BufferedReader(new InputStreamReader(resource,
StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
}
You can use Apache Commons IOUtils#readLines:
List<String> doc = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);

writing to file: the difference between stream and writer

Hi I have a bit of confusion about the stream to use to write in a text file
I had seen some example:
one use the PrintWriter stream
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fname)));
out.println(/*something to write*/);
out.close();
this instead use:
PrintStream out = new PrintStream(new FileOutputStream(fname));
out.println(/*something to write*/)
but which is the difference?both write in a file with the same result?
PrintWriter is new as of Java 1.1; it is more capable than the PrintStream class. You should use PrintWriter instead of PrintStream because it uses the default encoding scheme to convert characters to bytes for an underlying OutputStream. The constructors for PrintStream are deprecated in Java 1.1. In fact, the whole class probably would have been deprecated, except that it would have generated a lot of compilation warnings for code that uses System.out and System.err.
PrintWriter is for writing text, whereas PrintStream is for writing data - raw bytes. PrintWriter may change the encoding of the bytes to make handling text easier, so it might corrupt your data.
PrintWriter extends the class Writer, a class thinked to write characters, while PrintStream implements OutputStream, an interface for more generic outputs.

PrintWriter vs FileWriter in Java

Are PrintWriter and FileWriter in Java the same and no matter which one to use? So far I have used both because their results are the same. Is there some special cases where it makes sense to prefer one over the other?
public static void main(String[] args) {
File fpw = new File("printwriter.txt");
File fwp = new File("filewriter.txt");
try {
PrintWriter pw = new PrintWriter(fpw);
FileWriter fw = new FileWriter(fwp);
pw.write("printwriter text\r\n");
fw.write("filewriter text\r\n");
pw.close();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
According to coderanch.com, if we combine the answers we get:
FileWriter is the character representation of IO. That means it can be used to write characters. Internally FileWriter would use the default character set of the underlying OS and convert the characters to bytes and write it to the disk.
PrintWriter & FileWriter.
Similarities
Both extend from Writer.
Both are character representation classes, that means they work with characters and convert them to bytes using default charset.
Differences
FileWriter throws IOException in case of any IO failure, this is a checked exception.
None of the PrintWriter methods throw IOExceptions, instead they set a boolean flag which can be obtained using checkError().
PrintWriter has an optional constructor you may use to enable auto-flushing when specific methods are called. No such option exists in FileWriter.
When writing to files, FileWriter has an optional constructor which allows it to append to the existing file when the "write()" method is called.
Difference between PrintStream and OutputStream: Similar to the explanation above, just replace character with byte.
PrintWriter has following methods :
close()
flush()
format()
printf()
print()
println()
write()
and constructors are :
File (as of Java 5)
String (as of Java 5)
OutputStream
Writer
while FileWriter having following methods :
close()
flush()
write()
and constructors are :
File
String
Link: http://www.coderanch.com/t/418148/java-programmer-SCJP/certification/Information-PrintWriter-FileWriter
Both of these use a FileOutputStream internally:
public PrintWriter(File file) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
false);
}
public FileWriter(File file) throws IOException {
super(new FileOutputStream(file));
}
but the main difference is that PrintWriter offers special methods:
Prints formatted representations of
objects to a text-output stream. This
class implements all of the print
methods found in PrintStream. It does
not contain methods for writing raw
bytes, for which a program should use
unencoded byte streams.
Unlike the PrintStream class, if
automatic flushing is enabled it will
be done only when one of the println,
printf, or format methods is invoked,
rather than whenever a newline
character happens to be output. These
methods use the platform's own notion
of line separator rather than the
newline character.
A PrintWriter has a different concept of error handling. You need to call checkError() instead of using try/catch blocks.
PrintWriter doesn't throw IOException.You should call checkError() method for this purpose.
The java.io.PrintWriter in Java5+ allowed for a convenience method/constructor that writes to file.
From the Javadoc;
Creates a new PrintWriter, without automatic line flushing, with the specified file. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will encode characters using the default charset for this instance of the Java virtual machine.
just to provide more info related to FLUSH and Close menthod related to FileOutputStream
flush() ---just makes sure that any buffered data is written to disk flushed compltely and ready to write again to the stream (or writer) afterwards.
close() ----flushes the data and closes any file handles, sockets or whatever.Now connection has been lost and you can't write anything to outputStream.
The fact that java.io.FileWriter relies on the default character encoding of the platform makes it rather useless to me. You should never assume something about the environment where your app will be deployed.

How to save content of a page call into a file in jsp/java?

In jsp/java how can you call a page that outputs a xml file as a result and save its result (xml type) into a xml file on server. Both files (the file that produces the xml and the file that we want to save/overwrite) live on the same server.
Basically I want to update my test.xml every now and then by calling generate.jsp that outputs a xml type result.
Thank you.
If the request is idempotent, then just use java.net.URL to get an InputStream of the JSP output. E.g.
InputStream input = new URL("http://example.com/context/page.jsp").openStream();
If the request is not idempotent, then you need to replace the PrintWriter of the response with a custom implementation which copies the output into some buffer/builder. I've posted a code example here before: Capture generated dynamic content at server side
Once having the output, just write it to disk the usual java.io way, assuming that JSP's are already in XHTML format.
Register a filter that adds a wrapper to your response. That is, it returns to the chain a new HttpServletResponse objects, extending the original HttpServletResponse, and returning your custom OutputStream and PrintWriter instead of the original ones.
Your OutputStream and PrintWriter calls the original OutputStream and PrintWriter, but also write to a your file (using a new FileOutputStream)
Why don't you use a real template engine like FreeMarker? That would be easier.

Categories

Resources