Java sockets and file Streaming - java

I have a basic question on files ... It seems that I am stuck.
I am creating a server-client socket. The client sends a random number of integers to the server using an iterative way and the methods bellow.
//BufferedWriter out = new BufferedWriter(new OutputStreamWriter (sock.getOutputStream()));
out.write(number);
out.flush();
The server accepts them like this:
//BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
number=in.read();
All , I want is the server to store all these integers into a file (myfile.txt for example) and then I want to read this file as a string (with all integers) in order to send it back to the client.
Any ideas? I tried few methods but right now I am totally stuck and I really cant think clear... I would really appreciate it if someone could help me out a bit.
Cheers
EDIT: I tried these methods so far
FileOutputStream fos = new FileOutputStream("myfile.txt");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(number);
And then I tried to read this with
FileInputStream fin=new FileInputStream("myfile.txt");
DataInputStream dis = new DataInputStream(fin);
int numbers = dis.read();
But all I get is the number 0. :S

Writing the file could be achieved like this
FileOutputStream fileOutputStream = new FileOutputStream("test.txt");
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
// Make sure to write the data as a String
bufferedWriter.write("" + number);
bufferedWriter.close();
fileOutputStream.close();
Afterwards, reading can be achieved like this
FileInputStream fileInputStream = new FileInputStream("test.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String line = bufferedReader.readLine();
number = Integer.valueOf(line);
Advantage of using a BufferedWriter and a BufferedReader is that you can read / write Strings and have a human readable file. Using a DataOutputStream, you'd have a binary file, and you'll have do conversion from / to your data format yourself.
Regarding your code example:
dis.read();
will return you the number of bytes read, not the actual data. You'd do that using
dis.readInt();

Related

read line from sequence of byte arrays

I receive data from Bluetooth BLE as follow in 250 bytes chunk at most.
onDataReceived(byte[] data) {
my_readline(); // <-- how could I implement this
}
the data are string but chuncked. so what is the proper way to detect lines from incomming byte arrays. or it would be good as well if it is possible to convert received data to inputStream as well.
You could do it with an ByteArrayInputStream and turn that into an BufferedReader. It is not very clean altough it should work.
InputStream inputStream = new ByteArrayInputStream(data);
BufferedReader buffReader = new BufferedReader(new InputStreamReader(inputStream));
You can convert byte array to String,
String inputStr = new String(data, "UTF-8");
And if you want to convert to InputStream,
InputStream dataInputStream = new ByteArrayInputStream(data);

Problem with writing into txt file on my server from a Java program

I'm having this problem when trying to write into a txt file on my server from a Java program. Even though it writes the text, it writes some strange chars in front of it. My code looks like this:
URL urlOutput = new URL("ftp://username:password#ftp.matsworld.io");
URLConnection urlc = urlOutput.openConnection();
OutputStream os = urlc.getOutputStream();
OutputStream buffer = new BufferedOutputStream(os);
ObjectOutput output = new ObjectOutputStream(buffer);
output.writeObject("Hello world!");
output.close();
buffer.close();
os.close();
And this is what appears in the txt file:
¨ŪtKVHello world!
Thanks for help!
ObjectOutputStream is used for object serialization. The part preceding "Hello world!" is the "bookkeeping" information saved by the object output stream for the object input stream to figure out what kind of object is being restored.
Use PrintStream for outputting textual information:
URL urlOutput = new URL("ftp://username:password#ftp.matsworld.io");
URLConnection urlc = urlOutput.openConnection();
OutputStream os = urlc.getOutputStream();
OutputStream buffer = new BufferedOutputStream(os);
PrintStream output = new PrintStream(buffer);
output.writeLine("Hello world!");
output.close();
buffer.close();
os.close();

BufferedReader readLine() have weird characeters

I have found a issue when I write and read data from sockets, in this time the socket are already open.
The code from server:
<pre>ServerSocket server = new ServerSocket(2001);
Socket socket = server.accept();
while(true){
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readString = br.readLine();
System.out.println("result:\n"+readString)
}</pre>
The test I made from a client
<pre>Socket socket = new Socket("localhost", 2001);
Scanner consoleRead= new Scanner(System.in);
consoleRead.useDelimiter("\n");
ObjectOutputStream oo = new ObjectOutputStream(socket.getOutputStream());
while(true){
String s = consoleRead.next();
oo.writeUTF(s+System.lineSeparator());
oo.flush();
}</pre>
The first line is read perfectly... But the rest begin with weird characters.
Regards
If you are writing with ObjectOutputStream then read with ObjectInputStream insted of InputStreamReader
writeUTF()
Primitive data write of this String in modified UTF-8 format. Note that there is a significant difference between writing a String into the stream as primitive data or as an Object. A String instance written by writeObject is written into the stream as a String initially. Future writeObject() calls write references to the string into the stream.
Better is :- Write with OutputStreamWriter and read with InputStreamReader
For better understanding:- write the same thing in a file with ObjectOutputStream and then check what is getting written.

Can't use InputStream from Socket after writeObject

Here is the situation:
I have a ServerSocket ss, and "Socket socket = ss.accept();", then if I do this:
istream = socket.getInputStream();
ostream = socket.getOutputStream();
in = new BufferedReader(new InputStreamReader(istream));
out = new PrintWriter(new BufferedOutputStream(ostream));
/*
I use in/out few times
everything OK
*/
ObjectOutputStream oos = new ObjectOutputStream(ostream);
oos.writeObject(someobject);
/* probably code that solves the problem */
String line = in.readLine();
On the client side I have this code:
PrintWriter out = new PrintWriter(new BufferedOutputStream(socket.getOutputStream()),true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
/*
using in/out, no problems
*/
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
SomeObject so = (SomeObject)ois.readObject();
out.println("some text");
Everything is OK, until I send someobject. Client recieves object properly, no problems there. But I can't use socket anymore. If I do oos.close(), I get Exception that says "socket closed". If I do oos.reset() I get Exception with similar message. "socket reset". So what should I do? Is it possible to use same input and output streams after writeObject()?
What happens when I send "some text" is that I'm just getting nulls no matter how many times I call readLine(), I never get that "some text".
You can't use multiple type of stream/reader/writer on the same underlying socket. All your streams and readers and writers are buffered so they will all get thoroughly mixed up. Stick tone kind. Stick to one protocol. If you have object streams, use them for everything. And create them once for the life of the socket, not per message.

URL Connection (FTP) in Java - Simple Question

I have a simple question. I'm trying to upload a file to my ftp server in Java.
I have a file on my computer, and I want to make a copy of that file and upload it. I tried manually writing each byte of the file to the output stream, but that doesn't work for complicated files, like zip files or pdf files.
File file = some file on my computer;
String name = file.getName();
URL url = new URL("ftp://user:password#domain.com/" + name +";type=i");
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream();
//then what do I do?
Just for kicks, here is what I tried to do:
OutputStream os = urlc.getOutputStream();
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while(line != null && (!line.equals(""))) {
os.write(line.getBytes());
os.write("\n".getBytes());
line = br.readLine();
}
os.close();
For example, when I do this with a pdf and then try and open the pdf that I run with this program, it says an error occurred when trying to open the pdf. I'm guessing because I am writing a "\n" to the file? How do I copy the file without doing this?
Do not use any of the Reader or Writer classes when you're trying to copy the byte-for-byte exact contents of a binary file. Use these only for plain text! Instead, use the InputStream and OutputStream classes; they do not interpret the data at all, while the Reader and Writer classes interpret the data as characters. For example
OutputStream os = urlc.getOutputStream();
FileInputStreamReader fis = new FileInputStream(file);
byte[] buffer = new byte[1000];
int count = 0;
while((count = fis.read(buffer)) > 0) {
os.write(buffer, 0, count);
}
Whether your URLConnection usage is correct here, I don't know; using Apache Commons FTP (as suggested elsewhere) would be an excellent idea. Regardless, this would be the way to read the file.
Use a BufferedInputStream to read and BufferedOutputStream to write. Take a look at this post: http://www.ajaxapp.com/2009/02/21/a-simple-java-ftp-connection-file-download-and-upload/
InputStream is = new FileInputStream(localfilename);
BufferedInputStream bis = new BufferedInputStream(is);
OutputStream os =m_client.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
int readCount;
while( (readCount = bis.read(buffer)) > 0) {
bos.write(buffer, 0, readCount);
}
bos.close();
FTP usually opens another connection for data transfer.
So I am not convinced that this approach with URLConnection is going
to work.
I highly recommend that you use specialized ftp client. Apache commons
may have one.
Check this out
http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html

Categories

Resources