I am trying the following code using the DataOutputStream. The OutputStream passed to the DataOutputStream is not printing anything. Please see my below code and pllease tell me anything wrong in this code.
public class DataStreamsExample {
public static void main(String[] args) throws IOException {
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter the First Number");
int i = dis.readInt();
System.out.println("Enter the Second Numebr");
int j= dis.readInt();
int total = i+j;
DataOutputStream dos = new DataOutputStream(System.out);
dos.writeInt(total);
}
}
Why are you using data output streams? Can't you use a Scanner for reading input?
Calling dos.flush() will print out your result though.
OutputStream is fundamentally a binary construct. If you want to write text data (e.g. from the console) you should use a Writer of some description. To convert an OutputStream into a Writer, use OutputStreamWriter. Then create a PrintWriter around the Writer, and you can read a line using PrintWriter.println().
You can replace follow line
DataOutputStream out = new DataOutputStream(out);
into this
PrintWriter out = new PrintWriter(new OutputStreamWriter(out));
The character encoding can then be explicitly specified in the constructor of OutputStreamWriter.
Related
I have to write both PrintWriter and DataOutputStream to print data onto my file. But PrintWriter is getting printed earlier than DataOutputStream though it comes after DataOutputStream in code.
Part of code:
import java.io.*;
import java.util.*;
public class file {
public static void main(String[] args) {
DataOutputStream dos=null;
PrintWriter pw=null;
try {
File f=new File("file.txt");
dos=new DataOutputStream(new FileOutputStream(f));
pw=new PrintWriter(f);
Scanner b=new Scanner(System.in);
for(int i=0;i<=4;i++) {
int h=b.nextInt();
b.nextLine();
dos.writeInt(h);
String s=b.nextLine();
int l=s.length();
dos.writeBytes(s);
pw.println();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
if(dos!=null)
try {
dos.close();
} catch(IOException e) {
e.printStackTrace();
}
pw.flush();
}
}
}
new line from pw is getting printed first and then data from dos.write(); how to avoid this?? and make it get in order?
Never mix a Writer and an OutputStream as they are used for different purpose, indeed a Writer is used to generate a text file (readable by a human being) and an OutputStream is used to generate a binary file (not readable by a human being), use only one of them according to your requirements.
Assuming that you decide to use only the DataOutputStream simply replace pw.println() with something like dos.write(System.lineSeparator().getBytes(StandardCharsets.US_ASCII)) to write the line separator into your file with your OutputStream. However please note that in a binary file adding a line separator doesn't really make sense since the file is not meant to be read by a human being.
I need to take a 10000 character string as input from user in a program in java. But when i use the normal way it gives NZEC error in ideone and spoj. How can i take such a string as an input ?
import java.io.*;
class st
{
public static void main(String args[])throws IOException
{
String a;
BufferedReader g=new BufferedReader(new InputStreamReader(System.in));
a=g.readLine();
}
}
BufferedReader uses a buffer that is large enough "for most purposes". 10000 characters is probably too large. Since you're using readLine, the reader is scanning characters read, looking for an end of line. After its internal buffer is full, and it still hasn't found an end of line, it throws an exception.
You could try setting the size of the buffer when you create the BufferedReader:
BufferedReader g=new BufferedReader(new InputStreamReader(System.in), 10002);
Or you could use use
BufferedReader.read(char[] cbuf, int off, int len)
instead. That would give you an array of char, and you'd need to convert it back to a String.
Just read until the buffer is full.
byte[] buffer = new byte[10000];
DataInputStream dis = new DataInputStream(System.in);
dis.readFully(buffer);
// Once you get here, the buffer is filled with the input of stdin.
String str = new String(buffer);
Take a look at Runtime Error (NZEC) in simple code to understand possible reasons for the error message.
I suggest you wrap the readLine() in a try/catch block and print the error message / stack trace.
I have written this program to write marks into the file called marks.txt, but why is the dos.writeInt() writing Ascii values into the file?
class Q5marks
{
public static void main(String a[])throws IOException`
{
int marks[]=new int[6]
File file = new File("marks.txt");
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
Scanner sc = new Scanner(System.in);
for(int i = 0;i<6;i++)
{
marks[i]=sc.nextInt();
System.out.println("marks "+(i+1)+" =>" +marks[i]);
dos.writeInt(marks[i]);
}
}
}
Replace your code with : dos.writeBytes(marks[i]+""); . It should work as desired by you .
i want to insert 65 65 65 65 65 65 but it writes A A A A A A into the file
Then you should be using PrintStream and not DataOutputStream.
It will write numerical values to the file because you've specified writeInt.
You may be looking to use:
doc.writeChar(marks[i]);
But I can't be too sure. Your question isn't quite clear enough.
Instead, use as PrintStream.
When you call dos.writeInt(marks[i]); don't think that it will write the int in human readable format( as normal text editor consider all as char so your 65 become A). It will write the byte value of int. You can read the file again using the readInt() method.
EDIT:
If you want it should write the int show that you can read it with normal text editor then
use the flowing code that use a FileWriter instead of DataOutputStream. And don't forget to close the writer.
class Q5marks
{
public static void main(String a[])throws IOException
{
int marks[]=new int[6];
File file = new File("marks.txt");
FileOutputStream fos = new FileOutputStream(file);
FileWriter writer=new FileWriter(file);
Scanner sc = new Scanner(System.in);
for(int i = 0;i<6;i++)
{
marks[i]=sc.nextInt();
System.out.println("marks "+(i+1)+" =>" +marks[i]);
writer.write(String.valueOf(marks[i])+" ");//a space is added to increase the readability
}
writer.close();
}
}
I am writing some code for a programming contest in java. The input to the program is given using stdin and output is on stdout. How are you folks testing programs that work on stdin/stdout? This is what I am thinking:
Since System.in is of type InputStream and System.out is of type PrintStream, I wrote my code in a func with this prototype:
void printAverage(InputStream in, PrintStream out)
Now, I would like to test this using junit. I would like to fake the System.in using a String and receive the output in a String.
#Test
void testPrintAverage() {
String input="10 20 30";
String expectedOutput="20";
InputStream in = getInputStreamFromString(input);
PrintStream out = getPrintStreamForString();
printAverage(in, out);
assertEquals(expectedOutput, out.toString());
}
What is the 'correct' way to implement getInputStreamFromString() and getPrintStreamForString()?
Am I making this more complicated than it needs to be?
Try the following:
String string = "aaa";
InputStream stringStream = new java.io.ByteArrayInputStream(string.getBytes())
stringStream is a stream that will read chars from the input string.
OutputStream outputStream = new java.io.ByteArrayOutputStream();
PrintStream printStream = new PrintStream(outputStream);
// .. writes to printWriter and flush() at the end.
String result = outputStream.toString()
printStream is a PrintStream that will write to the outputStream which in turn will be able to return a string.
EDITED: Sorry I misread your question.
Read with scanner or bufferedreader, The latter is much faster than the former.
Scanner jin = new Scanner(System.in);
BufferedReader reader = new BufferedReader(System.in);
Write to stdout with print writer. You can also print directly to Syso but this is slower.
System.out.println("Sample");
System.out.printf("%.2f",5.123);
PrintWriter out = new PrintWriter(System.out);
out.print("Sample");
out.close();
I am writing some code for a programming contest in java. The input to the program is given using stdin and output is on stdout. How are you folks testing programs that work on stdin/stdout?
Another way to send characters to System.in is to use PipedInputStream and PipedOutputStream. Maybe something like the following:
PipedInputStream pipeIn = new PipedInputStream(1024);
System.setIn(pipeIn);
PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
// then I can write to the pipe
pipeOut.write(new byte[] { ... });
// if I need a writer I do:
Writer writer = OutputStreamWriter(pipeOut);
writer.write("some string");
// call code that reads from System.in
processInput();
On the flip side, as mentioned by #Mihai Toader, if I need to test System.out then I do something like:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
// call code that prints to System.out
printSomeOutput();
// now interrogate the byte[] inside of baos
byte[] outputBytes = baos.toByteArray();
// if I need it as a string I do
String outputStr = baos.toString();
Assert.assertTrue(outputStr.contains("some important output"));
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I am not sure how you are supposed to read in from system input from a Java file.
I want to be able to call java myProg < file
Where file is what I want to be read in as a string and given to myProg in the main method.
Any suggestions?
You can use System.in to read from the standard input. It works just like entering it from a keyboard. The OS handles going from file to standard input.
import java.util.Scanner;
class MyProg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Printing the file passed in:");
while(sc.hasNextLine()) System.out.println(sc.nextLine());
}
}
Well, you may read System.in itself as it is a valid InputStream. Or also you can wrap it in a BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
In Java, console input is accomplished by reading from System.in. To obtain a character based
stream that is attached to the console, wrap System.in in a BufferedReader object.
BufferedReader supports a buffered input stream. Its most commonly used constructor
is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being
created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader,
which converts bytes to characters.
To obtain an InputStreamReader object that is linked to System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream.
Putting it all together, the following line of code creates a BufferedReader that is connected
to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console
through System.in.
This is taken from the book Java- The Complete Reference by Herbert Schildt
Use System.in, it is an InputStream which just serves this purpose
You would read from System.in just like you would for keyboard input using, for example, InputStreamReader or Scanner.
You can call java myProg arg1 arg2 ... :
public static void main (String args[]) {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
}
You probably looking for something like this.
FileInputStream in = new FileInputStream("inputFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
class myFileReaderThatStarts with arguments
{
class MissingArgumentException extends Exception{
MissingArgumentException(String s)
{
super(s);
}
}
public static void main(String[] args) throws MissingArgumentException
{
//You can test args array for value
if(args.length>0)
{
// do something with args[0]
}
else
{
// default in a path
// or
throw new MissingArgumentException("You need to start this program with a path");
}
}