Consider the following code-
import java.io.*;
public class test
{
public static void main(String[] args)
{
PrintWriter out= new PrintWriter(System.out);
out.println(1);
out.close();
}
}
I run it on bluej for the first time and get output 1 on console. On running it again i get no output at all and same is the case for any subsequent tries.
Would love to know why this is happening.
Ok, the problem why this method only works once is, that the PrintWriter.close() method also closes the parent Stream, in this case System.out.
So when you call this method the next time, System.out will be closed, and nothing will be printed.
So the solution is not to close the PrintWriter.
But in this case, nothing is printed, because the output of the PrintWriter is not flushed. To do that, you either have to call out.flush() yourself or use a constructor which enables auto-flushing on line-endings.
tl;dr:
Either use this:
import java.io.*;
public class test
{
public static void main(String[] args)
{
PrintWriter out= new PrintWriter(System.out);
out.println(1);
out.flush();
}
}
or this:
import java.io.*;
public class test
{
public static void main(String[] args)
{
PrintWriter out= new PrintWriter(System.out, true);
out.println(1);
}
}
Related
I have this code which pulls the source code from the website listed. When the text is printed out each letter is in a different line. I need the line setup to be the same as the source code on chrome. How could I get it to print out like that?
package downloader;
import java.io.*;
import java.util.*;
import java.net.*;
public class Scannerup {
public static void main(String args[]) throws IOException
{
URL obj = new URL("https://www.papajohns.com/");
URLConnection con = obj.openConnection();
InputStream in1 = con.getInputStream();
int i;
do {
i = in1.read();
if(i!=-1)
{
System.out.println((char)i);
}
}
while(i!=-1);
}
}
Notice this
if(i!=-1)
{
System.out.println((char)i); ----------> You are using println
}
Change it to
if(i!=-1)
{
System.out.print((char)i);
}
print() - will print the required output on the same line again and again. (This is what you should of used)
println() - will print the output in the next line(This is what you use in your code)
I have been trying to execute this program, but it shows error saying that urlconnectionreader cannot be resolved. I'm new to programming. Can someone help me with this?
This is my code:
import java.net.*;
import java.io.*;
public class ReadTextFromUrl {
public static String getText(String url) throws Exception {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
}
public static void main(String[] args) throws Exception {
// enter code here
String content = URLConnectionReader.getText(args[0]);
System.out.println(content);
}
}
There are Many Libraries to read text from URL,
You can Try jsoup library to read or extract only text.
import java.io.IOException;
import org.jsoup.Jsoup;
public class ReadTextFromURL {
public static void main(String[] args) throws IOException {
String text = Jsoup.connect("https://stackoverflow.com/questions/40741265/read-only-text-from-url-using-java").get().text();
System.out.println(text);
}
}
In your case the class name should be URLConnectionReader or you can change the the calling function via your class name .
String content = ReadTextFromUrl.getText(args[0]);
what you need to study more is objects.you must know that the classes are the blueprints.you cant use a saw blueprint to saw a tree.you need the saw itself.and by creating a object from that class you will have the saw.so when you have the saw in your hands you can saw the tree.making an object from a class works exactly the same.and using the ways(methods) to saw the tree with the actual saw is like using the methods of the class.
lets think you have a class named Saw and it has a method named sawTheTree.
public class Saw {
public void sawTheTree {
// do the sawing
}
}
its the blueprint by now.to use this saw and the method you need this :
Saw saw = new Saw();
now you have the saw in your hands.lets go and saw the tree.for this you need this code in your main method or where ever you feel the need of sawing the tree.
saw.sawTheTree();
now the the saw will saw the tree for you.
P.S: in your code you have declared the getText method static so you don't need the object creation part.if you are asking why look again at static statement description.but to use a non static method from a class you need to create the object.
Is there a way in which, from a function, I print a String in with System.out.print() and then read it from another function?
something like:
void printC(String foo){
System.out.print(foo);
}
void read(){
String c;
while(something){
printC(somethingElse);
c = System.console.readLine();
JOptionPane.showMessageDialog(c);
}
}
No, you can't. As other people have commented, you probably just want an internal data structure to connect different components.
In command-line programs, the standard input and standard output (plus standard error) are completely independent streams. It's typical for all three to be connected to a single virtual terminal, but they can be redirected independently from the shell, such as by using a pipeline or files.
Think about what if the input of your program is coming from a file and the output is being piped to another program; trying to "get back" the output doesn't make any sense.
Try PipedOutputStream.
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Test extends JFrame {
void printC(String foo){
System.out.print(foo);
}
void read() throws IOException{
String c = "";
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
System.setOut(new PrintStream(pipeOut));
Scanner sc = new Scanner(pipeIn);
while(!c.equalsIgnoreCase("Quit")){
printC("Test\n");
c = sc.nextLine();
JOptionPane.showMessageDialog(this, c);
}
}
public static void main(String[] args) throws IOException {
Test t = new Test();
t.read();
}
}
Why do you want to do this? Is it so that you can print something to the screen or so that you can create events?
If you particularly want to pass messages to the screen AND also another part of your application; a simple solution could involve creating your own PrintStream class. You can deal with the object in the same way as you would otherwise deal with System.out (as that's a PrintStream too).
Something along the lines of this:
public class FancyStream extends PrintStream
{
LinkedList<String> messageQueue = new LinkedList<>();
#Override
public void println(String line)
{
System.out.println(line);
messageQueue.add(line);
}
public String getLine()
{
return messageQueue.pop();
}
}
However, if you want events (as you've suggested in the comments), this is not the way to do it!
You should take a look at the Observer pattern for dealing with events. The wikipedia article about this is here.
There's plenty of other resources to learn about the Observer pattern if you do a Google search. Java even has a built in Observable class and Observer interface that may solve your problem.
I am testing a output stream in java something like below.
Writer outputStream = getOutputStream(fileName);
if(outputStream != null) {
try {
outputStream.write(inputText);
}
finally {
outputStream.close();
}
}
else {
throw new IOException("Output stream is null");
}
I am write a mockito test as below
public void testFileWrite() throws IOException {
when(testObj.getOutputStream(outputFileNameValidValue)).thenReturn(outputStreamMock);
doNothing().when(outputStreamMock).write(Matchers.anyString());
doNothing().when(bufferedReaderMock).close();
testObj.write(outputFileNameValidValue, reveredFileInput);
verify(outputStreamMock).write(Matchers.anyString());
verify(outputStreamMock).close();
}
The problem is when you create OutputStreamWriter(new FileOutputStream(filename)) a physical file on the disk is created.
Can we test Outputstream.write without actually writing a file on the disk?
Thanks
Anand
You can use ByteArrayOutputStream which writes the data in memory. You can read this with a ByteArrayInputStream.
An alternative is to write an expecting OutputStream which fails as soon as you attempt to write an incorrect byte. This can be helpful to see exactly where/why a test fails.
You could try using System.out for your output which is actually a Printstream, which is a subclass of OutputStream
see:
http://docs.oracle.com/javase/6/docs/api/java/lang/System.html
http://docs.oracle.com/javase/6/docs/api/java/io/PrintStream.html
As other suggested already you need to be able to inject a mocked OutputStream in your class under test. As your class under test needs a OutputStream which writes into a given file, you will need to inject a mockable OutputStreamFactory into your class under test.
I have this code for you which is fully self contained:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.IOException;
import java.io.OutputStream;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
#RunWith(MockitoJUnitRunner.class)
public class Test9328173 {
private ClassUnderTest testObj;
#Mock
private OutputStreamFactory factory;
#Mock
private OutputStream stream;
#Before
public void setUp() throws Exception {
testObj = new ClassUnderTest();
testObj.factory = factory;
}
#Test
public void testFileWrite() throws Exception {
when(factory.create("filename")).thenReturn(stream);
testObj.write("filename", new byte[]{1, 2, 3});
verify(stream).write(new byte[]{1, 2, 3});
verify(stream).close();
}
private class ClassUnderTest {
private OutputStreamFactory factory;
public void write(String filename, byte[] content) throws IOException {
OutputStream stream = factory.create(filename);
try {
stream.write(content);
} finally {
stream.close();
}
}
}
private interface OutputStreamFactory {
OutputStream create(String filename);
}
}
You should mock up your getOutputStream: is should return mocked output stream object. Invocation of new FileOutputStream indeed creates file on disk.
Theoretically you can mock up file system itself but it is much more complicated.
And BTW if(outputStream != null) is redundant: stream can never be null. If it cannot be created the method should throw exception. It is not C, it is Java. :)
You should have the mocked getOutputStream(String) return a java.io.StringWriter and you can then assert that the expected content was written.
public void testFileWrite() throws IOException {
StringWriter writer = new StringWriter();
when(testObj.getOutputStream(outputFileNameValidValue)).thenReturn(writer);
testObj.write(outputFileNameValidValue, reveredFileInput);
assertEquals(reveredFileInput, writer.toString());
verify(writer).close();
}
I have one method whose return type is void and it prints directly on console.
However I need that output in a String so that I can work on it.
As I can't make any changes to the method with return type void I have to redirect that output to a String.
How can I redirect it in Java?
If the function is printing to System.out, you can capture that output by using the System.setOut method to change System.out to go to a PrintStream provided by you. If you create a PrintStream connected to a ByteArrayOutputStream, then you can capture the output as a String.
Example:
// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
// IMPORTANT: Save the old System.out!
PrintStream old = System.out;
// Tell Java to use your special stream
System.setOut(ps);
// Print some output: goes to your special stream
System.out.println("Foofoofoo!");
// Put things back
System.out.flush();
System.setOut(old);
// Show what happened
System.out.println("Here: " + baos.toString());
This program prints just one line:
Here: Foofoofoo!
Here is a utility Class named ConsoleOutputCapturer. It allows the output to go to the existing console however behind the scene keeps capturing the output text. You can control what to capture with the start/stop methods. In other words call start to start capturing the console output and once you are done capturing you can call the stop method which returns a String value holding the console output for the time window between start-stop calls. This class is not thread-safe though.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
public class ConsoleOutputCapturer {
private ByteArrayOutputStream baos;
private PrintStream previous;
private boolean capturing;
public void start() {
if (capturing) {
return;
}
capturing = true;
previous = System.out;
baos = new ByteArrayOutputStream();
OutputStream outputStreamCombiner =
new OutputStreamCombiner(Arrays.asList(previous, baos));
PrintStream custom = new PrintStream(outputStreamCombiner);
System.setOut(custom);
}
public String stop() {
if (!capturing) {
return "";
}
System.setOut(previous);
String capturedValue = baos.toString();
baos = null;
previous = null;
capturing = false;
return capturedValue;
}
private static class OutputStreamCombiner extends OutputStream {
private List<OutputStream> outputStreams;
public OutputStreamCombiner(List<OutputStream> outputStreams) {
this.outputStreams = outputStreams;
}
public void write(int b) throws IOException {
for (OutputStream os : outputStreams) {
os.write(b);
}
}
public void flush() throws IOException {
for (OutputStream os : outputStreams) {
os.flush();
}
}
public void close() throws IOException {
for (OutputStream os : outputStreams) {
os.close();
}
}
}
}
Although this question is very old and has already very good answers I want to provide an alternative. I created a library specifically for this use case. It is called Console Captor and you can add it with the following snippet:
<dependency>
<groupId>io.github.hakky54</groupId>
<artifactId>consolecaptor</artifactId>
<version>1.0.0</version>
<scope>test</scope>
</dependency>
Example class
public class FooService {
public void sayHello() {
System.out.println("Keyboard not responding. Press any key to continue...");
System.err.println("Congratulations, you are pregnant!");
}
}
Unit test
import static org.assertj.core.api.Assertions.assertThat;
import nl.altindag.console.ConsoleCaptor;
import org.junit.jupiter.api.Test;
public class FooServiceTest {
#Test
public void captureStandardAndErrorOutput() {
ConsoleCaptor consoleCaptor = new ConsoleCaptor();
FooService fooService = new FooService();
fooService.sayHello();
assertThat(consoleCaptor.getStandardOutput()).contains("Keyboard not responding. Press any key to continue...");
assertThat(consoleCaptor.getErrorOutput()).contains("Congratulations, you are pregnant!");
consoleCaptor.close();
}
}
If you are using Spring Framework, there is a really easy way to do this with OutputCaptureExtension:
#ExtendWith(OutputCaptureExtension.class)
class MyTest {
#Test
void test(CapturedOutput output) {
System.out.println("ok");
assertThat(output).contains("ok");
System.err.println("error");
}
#AfterEach
void after(CapturedOutput output) {
assertThat(output.getOut()).contains("ok");
assertThat(output.getErr()).contains("error");
}
}