Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to write a program that just reads and write an unbuffered steam, and reads and writes a buffered stream. Following the example on the java docs, I've got this for my buffered stream, which works fine.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("unbufferedread.txt");
outputStream = new FileWriter("unbufferedwrite.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
// Add finally block incase of errors.
// Display error if input file is not found.
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
However the Java docs say "Here's how you might modify the constructor invocations in the CopyCharacters example to use buffered I/O:".
inputStream = new BufferedReader(new FileReader("bufferedread.txt"));
outputStream = new BufferedWriter(new FileWriter("bufferedwrite.txt"));
My question is how to implement it. Is it possible to add it all to one class? When I try to add it, I get an error saying:
"Cannot find symbol - class BufferedReader"
Any help would be great. Thanks.
You have to import the java.io.BufferedReader and java.io.BufferedWriter classes. Based on the code you posted, you aren't doing that. So just add the two lines:
import java.io.BufferedReader;
import java.io.BufferedWriter;
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to get a copy of the content from the stream without consuming it. My plan is to use this original stream in the later of the code. Following is the sample code I tried to check this. My intention is to keep the original InputStream for future use after getting a copy
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class StreamTest {
public static void main(String[] args) {
try {
InputStream inputstream = new FileInputStream("resource.txt"); // content of the file is 'test'
ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(inputstream, baos);
byte[] bytes = baos.toByteArray();
System.out.println("copied stream : " + new String(bytes));
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(inputstream));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + System.lineSeparator());
}
System.out.println("original stream : " + sb.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
but still, when I access the original stream, after coping it, I still see that the original stream is consumed. See below output
copied stream : test
original stream :
Can someone point out my mistake
Thanks
Sadly this is not possible by the nature of streams.
In order to copy the data from the stream, you need to first extract it. By extracting it, you consume the stream.
But do not worry, there should be a solution for your specific use case. Maybe open another stream (if you know the source of the stream gives the same data every time - as in a file - , you can use Supplier everywhere you would use the InputStream, so that a new stream is created whenever necessary), or you can check out this post for creating more streams with the same data: https://stackoverflow.com/a/5924132/3102234
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
how to generate text file named as a user's name while generating receipt for him/her when he purchases a book,in java console based application.Help me out.
import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;
public class BookApplication {
public static void main(String[] args) {
try {
System.out.println("Hi , Enter Your Name ?");
Scanner scanner =new Scanner(System.in);
String username= scanner.nextLine();
String MY_OUTPUT_PATH="";//your path where you want your file
boolean bookPurchased=true; // Do your code for bookpurchase
if(bookPurchased){
File receipt= new File(MY_OUTPUT_PATH+ File.separator+username+".txt");
FileOutputStream outputStream =new FileOutputStream(receipt);
String sampleData=username+" has purchased a book for rs.500";
outputStream.write(sampleData.getBytes());
outputStream.close();
}
} catch (Exception e) {
System.out.println(e);
}
}
}
This is what I can give you from your Question. Try working on what you want, then ask Questions.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Guys please suggest me some good way to handle below in java.
I need to open an FIFO , check if there is any error in opening , then
Read from the Fifo and write into an File .
I will really glad if anyone could help me with this .
To read a fifo with java, you treat it like a regular file, I used the code below to verify
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.ByteArrayOutputStream;
class catfile {
public static void main(String[] args) throws java.io.FileNotFoundException, java.io.IOException {
byte[] b = getBytesFromInputStream(new FileInputStream(args[0]));
System.out.print(new String(b));
}
public static byte[] getBytesFromInputStream(InputStream is) throws java.io.IOException {
ByteArrayOutputStream res = new ByteArrayOutputStream();
byte[] bytes = new byte[0x10000]; /* 0x10000 = 65536 */
int numRead = 0;
while ((numRead = is.read(bytes, 0, bytes.length)) >= 0) {
res.write(bytes, 0, numRead);
}
return res.toByteArray();
}
}
the test went as follows
$ rm -f aaa; mkfifo aaa; (sleep 5; date >> aaa) &
$ javac catfile.java && java -ea -cp . catfile aaa
Thu Dec 5 08:18:51 UTC 2013
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to do a socket connection for client and server to display the list of files. but below code is not taking any input from server or giving output to client. Please help.
Server
package javaapplicationthread;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
public class zs {
public static int reads,red;
public static void main(String[] args)
{
int flg=0;
try{while(true){
ServerSocket serverSocket = new ServerSocket(1312);
Socket clientSocket = serverSocket.accept();
BufferedReader bufferedReader;
PrintWriter outk=new PrintWriter(clientSocket.getOutputStream(),true);
bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = bufferedReader.readLine();
System.out.println("input is"+ inputLine);
outk.write("abc");
File inputFolder = new File(inputLine);
System.out.println("control is being sent to traverse");
traverse(inputFolder, "");
}
}
catch (IOException ex) {
System.out.println("my exception is"+ex)
System.out.println(leftIndent + parentNode.getName());
}
}}
In the client, when you do redd = b.readLine(); you are asking to read an entire line. But in the server you haven't sent an entire line: you've only asked it to write three characters:
outk.write("abc");
None of those three characters is actually sent, however, because the PrintWriter buffers them temporarily. To fix it, change that line to:
outk.println("abc");
Or:
outk.write("abc\n");
outk.flush();
After that change, the client successfully displays: result is abc.
it is not giving any errors
They're both giving errors... The client throws an exception when the readLine call fails. The server throws an exception when it begins the next iteration of the while(true) loop and tries to recreate the socket it is still using. You probably want to move the creation of the ServerSocket outside the while loop.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
To execute process/command in bash from java one can use the following class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
public class CmdExecutor {
public CmdExecutor(){
}
public void exe(String [] args) throws IOException{
if (args.length <= 0) {
System.out.println("empty command");
return;
}
Process process = new ProcessBuilder(args).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:",
Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
However. What if the process don't terminate(yet). It does calculations and output it in the shell. I want to be able to run the process in another thread and get changes in the output, like frame by frame strings. How can this be achieved?
Check out
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html
You may want to have one thread (producer) reading process output, and putting them into a LinkedBlockingQueue (queue.put), then have another thread (consumer) to get elements from the queue (queue.poll) and process it.