I am coding a function which will check if file CQ.txt exists and if so, read from it. I have been having an issue where I have declared a printwriter outside of the while loop. Later in the application, it is supposed to write Question 1: correct or Question 2: correct to the file.
But, it does not. It creates the text file but when I check it, it shows up as empty.
Here is the code, thank you in advance:
package receiverhost;
import java.io.*;
import java.net.*;
public class ReceiverHost {
public static void main(String[] args) throws Exception {
//set up socket on port 5000
ServerSocket Server = new ServerSocket(5000);
//set up "cookie"/ text file to be written to/ read from eventually
Writer DB = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("CQ.txt"), "utf-8"));
System.out.println("TCPServer Waiting for client on port 5000");
while(true){
//declare string fromclient
String fromclient;
Socket connected = Server.accept();
System.out.println(" The client" + " " + connected.getInetAddress() + ":" + connected.getPort() + " is connected ");
//read/ retrieve client output stream
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connected.getInputStream()));
fromclient = inFromClient.readLine();
if(fromclient.equals("Q1C")){
//write to CQ.txt
DB.write("Q1: correct");
}
if(fromclient.equals("Q2C")){
//write to CQ.txt
DB.write("Q2: correct");
}
}
}
}
You should call 'write' method on BufferedWriter, and later 'close' it. Here is an example:
How to Write text file Java
BufferedWriter as the name suggests buffers the write to file. Any write to BufferedWriter will be written to in memory buffers not to the file directly.
this is done for efficiency purposes and in order to save CPU time wasted for IO .
Each time you invoke bufferedWriter.write it appends the data to buffer, writes the buffer data to file only if Buffer croses the threshold , either default or supplied by BufferedWriter(FileWriter,BufferSize) constructor .
It is recomended to flush the writer and close it after you have all the data written to bufferedWriter.
ideally a sample code would look like
Writer DB = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("CQ.txt"), "utf-8"));
DB.write("Dummy Data1 ");
DB.write("Dummy Data2");
DB.flush();
DB.close();
after close and flush you should be able to see all your data in the file.
Related
I used a regular expression to parse a text file to use the resulted group one and two as follows:
write group two in another file
make its name to be group one
Unfortunately, No data is written on the file!
I did not figure out where is the problem, here is my code:
package javaapplication5;
import java.io.*;
import java.util.regex.*;
public class JavaApplication5 {
public static void main(String[] args) {
// TODO code application logic here
try {
FileInputStream fstream = new FileInputStream("C:/Users/Welcome/Desktop/End-End-Delay.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
File newFile1= new File("C:/Users/Welcome/Desktop/AUV1.txt");
FileOutputStream fos1= new FileOutputStream(newFile1);
BufferedWriter bw1= new BufferedWriter(new OutputStreamWriter(fos1));
String strLine;
while ((strLine = br.readLine()) != null) {
Pattern p = Pattern.compile("sender\\sid:\\s(\\d+).*?End-End\\sDelay:(\\d+(?:\\.\\d+)?)");
Matcher m = p.matcher(strLine);
while (m.find()) {
String b = m.group(1);
String c = m.group(2);
int i = Integer.valueOf(b);
if(i==0){
System.out.println(b);
bw1.write(c);
bw1.newLine();
}
System.out.println(b);
// System.out.println(c);
}
}
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Can anyone here help me to solve this problem and Identify it?
You are using BufferedWriter, and never flush (flushing writer pushes the contents on disk) your writer or even close it at the end of your program.
Due to which, before your content gets written in actual file on disk from BufferedWriter, the program exits and the contents get lost.
To avoid this, either you can call flush just after writing contents in bw1,
bw1.write(c);
bw1.newLine();
bw1.flush();
OR
Before your program ends, you should call,
bw1.close(); // this ensures all content in buffered writer gets push to disk before jvm exists
Calling flush every time you write the data is not really recommended, as it defeats the purpose of buffered writing.
So best is to close the buffered writer object. You can do it in two ways,
Try-with-resources
Manually close the buffered writer object in the end, likely in the finally block so as to ensure it gets called.
Besides all this, you need to ensure that your regex matches and your condition,
if(i==0){
gets executed else code that is writing data in file won't get executed and of course in that case no write will happen in file.
Also, it is strongly recommended to close any of the resources you open like file resources, database (Connection, Statements, ResultSets) resources etc.
Hope that helps.
I am implementing my own HTTP server using sockets. In my java project folder I have a folder /root where all the files are saved which can be downloaded (test.html, test.jpg), so when the user browses to let's say localhost:8080/test.html my server takes the file, reads it and sends the bytes to the client's browser ,setting the right headers. Everything works fine with the .html extension but I have a problem with the images...the browser says that the file cannot be shown properly.
Here is the class which I use to read the bytes from the file:
public class FileRequestHandler {
public FileRequestHandler(){
}
/*
* Method which reads a text-file and turns it into a string
*/
public String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
}
after executing readFile() I get a string(I will call it response).
Now I set the headers and send them to the client:
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: image/jpeg");
out.println("Content-Length: " + response.length());
out.println();
out.println(response);
out.flush();
out is a PrintWriter object.
As I already mentioned, this method works with a html-file and everything is shown. What am I doing wrong? Maybe the encoding of the raw-bytes is incorrect or the headers were set incorrectly?
Thank you for the help!
An image is not a text file. Yet you are apparently reading it as text using a BufferedReader. That will mangle it ... and the use of readLine() and the line reassembly mangles it some more.
Either way, the browser will be unable to decode the mangled image that your server is sending.
You should use InputStream / OutputStream subtypes rather than Reader / Writer subtypes, and you should NOT attempt to convert the image into a string at any point.
(It is also a bad idea to attempt to implement an HTTP server using socket-level I/O ... but that's a different issue.)
BufferedReader reader = new BufferedReader(new FileReader (file));
The problem starts here. Readers and Writers are for text. Images are not text. You should be using an input stream, and writing bytes directly to an output stream, not collecting them in a String.
Here's the code I used, I get no errors or warnings but the file is empty, I created the aq.txt file and placed it in the workspace and it also shows in the project. I'm sure it's something stupid I'm missing but I just can't figure it out. Also, I tried all the other questions but the suggested answer is closing the stream and/or flushing it, both of which I do but they don't seem to work. Any help would be greatly appreciated!
Writer writer = null;
FileOutputStream fos= null;
try{
String xyz= "You should stop using xyz";
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(getFilesDir()+File.separator+"aq.txt")));
writer.write(xyz);
writer.flush();
}
catch(IOException e) {
System.out.println("Couldn't write to the file: " + e.toString());
}
finally{
if(writer != null){
try {
writer.close();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
}
Try like this:
fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(xyz);
writer.flush();
Context class provides a helper method Context.openFileOutput(String name, int mode) that will return a FileOutputStream to you for a file located in your applications Files directory.
I don't see any immediate reason why your way would not work, but I know I've used this other way successfully.
EDIT: After re-reading your question I think you are confused about where this file is going to be written to. It will not get written to the project folder inside of your workspace. This is going to be written to the internal storage of the android device that you run it on. Every application gets its own chunk of storage space located at \data\data\[package-name]\Files\ Your file is going to get written to there so you won't be able to immediately open it up and see the contents of it (unless your device is rooted.) You will instead have to open it up with java code and print its contents to the Log or some other output method in order to verify that your write did/did not work.
EDIT 2: Reading the file
FileInputStream in = openFileInput(FILE_NAME);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStreamReader);
String line = br.readLine();
Log.d("TAG", line);
This will read and output to the log the first line of the file.
This will certainly work :
File file = new File("fileName");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("data to write in the file.");
writer.flush();
I'm trying to make a Java TCP client and a node.js TCP server talk together.
This is my code at the moment :
The Java client
import java.net.;
import java.io.;
public class Client2{
public static void main(String[] args) throws Exception{
Socket s = new Socket("192.168.1.35",8500);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("abcdefgh");
dos.close();
s.close();
}
}
the Node.js Server
var net = require('net'),
server = net.createServer();
server.on('connection', function (client) {
console.log('Hello World !');
client.on('data', function(data) {
var message = data.toString('utf8');
console.log('***' + message +'***');
});
});
server.listen(8500);
This example will give this result back :
Hello World !
**abcdefgh***
but with this as input :
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
it gives this back :
Hello World !
***�abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz***
with this input :
qq32we3w87d 38s1d87s4df7s4d1+s2d7f+sfdsf4sà$àà3663%ç%&ç%&ç
it gives this back :
Hello World !
***#qq32we3w87d 38s1d87s4df7s4d1+s2d7f+sfdsf4sà$àà3663%ç%&ç%&ç***
tldr: Sometimes when logging the buffers, node adds characters (rectangles with numbers or ?) at the beginning or event cuts some characters at the start out.
- How can I log buffers and assign them to a variable the right way ?
I'm not an expert on DataOutputStream, but if it really is adding extra characters, you should use something else.
When I did server stuff, I used BufferedReader and BufferedWriter. It looks like this:
Socket s = new Socket(<<WEB ADDRESS AS STRING>>,<<PORT NO AS INT>>);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
//left out a bunch of lines. This is where you should read the lines
//of input (with an inner loop) and send stuff back
s.shutdownInput();
bw.flush();
s.shutdownOutput();
NOTE, IF YOU'RE GOING TO DEAL WITH LARGE PAGES, THIS COULD CAUSE A PROBLEM, AS THE BUFFEREDREADER AND BUFFEREDWRITER WILL FILL UP BEFORE YOU'RE READY. if this is a problem I'd look into the other Reader and Writer classes. They are quite plentiful, as I understand it, and one should suit your needs.
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(is));
String cmd=null;
while(is.available()<1){}
cmd = br.readLine();
System.out.println("cmd: "+cmd);
if(cmd.equals("search")){
String[] param = br.readLine().split(",");
for(String s:param){
System.out.println(s);
}
this the client code which accepts a string sent by server.but an exception is thrown in the line cmd=br.readLine()... a connection reset error..
server code is
Socket(InetAddress.getLocalHost(),1234);
OutputStream os = s.getOutputStream();InputStream is=s.getInputStream();
java.io.BufferedWriter bw=new java.io.BufferedWriter(new java.io.OutputStreamWriter(os));
String ss="search";
bw.println(ss);
bw.flush();
System.out.println("search cmded");
String param = "a,*,0,-1";
bw.println(param);
bw.flush();
System.out.println("param sent");
i've tried using print writer and the bufferedwriter but nothing is working correctly
so what could be the possible solution ???
also one thing worth mentioning is im using a listener service which creates a new server code mentioned above to handle particular client requests...
so wot could be soln now ??
In the server, your BufferedWriter is named bw but you're writing to pw.
Get rid of the available() test. You have it back to front, and it's not valid anyway. readLine() will block while there is no data. Just test the return value of readLine() for null, and break.