Java File transferring with Sockets error ArrayIndexOutOfBoundsException [closed] - java

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
When I run the client, it returns(an error): Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at java.io.BufferedOutputStream.write(Unknown Source)
at Sockets.FileSocketClient.main(FileSocketClient.java:14)
I understand where it is occurring[bos.write(mybytearray, 0, bytesRead);], I just don't understand WHY
Server
import java.io.*;
import java.net.*;
public class FileSocketServer {
public static void main(String args[]) throws IOException {
ServerSocket serverSocket = new ServerSocket(1235);
File myFile = new File("test.txt");
while(true) {
Socket socket = serverSocket.accept(); //Understand
byte[] mybytearray = new byte[(int)myFile.length()]; //Don't understand
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile)); //Don't understand
bis.read(mybytearray, 0, mybytearray.length); //Don't understand
OutputStream os = socket.getOutputStream(); //Don't understand
os.write(mybytearray, 0, mybytearray.length); //Don't understand
os.flush(); //Don't understand
socket.close(); //Don't understand
}
}
}
Client
package Sockets;
import java.io.*;
import java.net.*;
public class FileSocketClient {
public static void main(String args[]) throws IOException{
Socket socket = new Socket("GANNON-PC", 1235); //Understand
byte[] mybytearray = new byte[1024]; //Don't understand
InputStream is = socket.getInputStream(); //Don't understand
FileOutputStream fos = new FileOutputStream("mods//test.txt"); //Don't understand
BufferedOutputStream bos = new BufferedOutputStream(fos); //Don't understand
int bytesRead = is.read(mybytearray, 0, mybytearray.length); //Don't understand
bos.write(mybytearray, 0, bytesRead); //Don't understand
bos.close(); //
socket.close();
}
}

The proper way to send a file:
public void sendFile(Socket socket, File myFile) throws IOException {
DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); //get the output stream of the socket
dos.writeInt((int) myFile.length()); //write in the length of the file
InputStream in = new FileInputStream(myFile); //create an inputstream from the file
OutputStream out = socket.getOutputStream(); //get output stream
byte[] buf = new byte[8192]; //create buffer
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len); //write buffer
}
in.close(); //clean up
out.close();
}
Receive a file:
public void receiveFile(Socket socket, String fileName) throws IOException {
DataInputStream dis = new DataInputStream(socket.getInputStream()); //get the socket's input stream
int size = dis.readInt(); //get the size of the file.
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream(fileName); //stream to write out file
int totalBytesRead = 0;
byte[] buf = new byte[8192]; //buffer
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len); //write buffer
}
out.close(); //clean up
in.close();
}
The difference between this code and yours is first I send over the length of the file before I send the entire file. The file might be bigger than the buffer you have allocated for it, so you need a loop to read it incrementally.

Related

Index out of bound exception with inputstream data

I was trying to flush data in a file in my local machine to response. But at some point I get an IndexOutOfBoundsException.
FileInputStream inputStream = new FileInputStream(downloadFile);
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer, 0, 4096)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
The above code is what I was trying. The downloadFile path given is correct and it works till the while loop. But then the IndexOutOfBoundsException occurs. I tried it with inputStream.read(buffer) but that didn't work.
Give code is working perfectlly; since there is no information is given regarding the response object I have modify the OutputStream to FileOutputStream; just to test.
Below code segment is working perfectly.
public class Test
{
public static void main(String args[]) throws IOException
{
FileInputStream inputStream = new FileInputStream("C:\\readme.txt");
FileOutputStream outputStream = new FileOutputStream("D:\\readme1.txt");
//OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer, 0, 4096)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
}
}

Receiving file on connection timed out

I made a server that sends a text file to the client (Android) and I'm only getting the file when I'm getting connection timed out.
Why the "connection timed out" is happening in the first place? and also, it takes like 1 minute to the file to be received (1MB).
Server:
FileInputStream fis = new FileInputStream(
new File("123.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
byte[] mybytearray = new byte[8192];
OutputStream os;
try {
os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
int read;
while ((read = dis.read(mybytearray)) > 0) {
dos.write(mybytearray, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
Client:
InputStream in;
int Size = 0;
try {
Size = clientSocket.getReceiveBufferSize();
in = clientSocket.getInputStream();
DataInputStream dis = new DataInputStream(in);
byte[] buffer = new byte[Size];
int read;
while ((read = dis.read(buffer)) > 0) {
fos.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
Any idea how to fix this problem?
You don't close stream on the server side. So nobody knows that this is the end of stream and wait continues till time out. Add close() like this:
os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
int read;
while ((read = dis.read(mybytearray)) > 0) {
dos.write(mybytearray, 0, read);
}
os.close();
Also, on client side you should expect zero input. Its is OK for slow connection. Only -1 means that connection is closed. Change code like this:
while ((read = dis.read(buffer)) > -1)

Java "invalid stream header" error

I'm having issues sending a file from one person to another in my program, I get a "invalid stream header" error. Here is the code for sending and receiving the file, respectively:
private void sendFile(Socket socket, File file) throws IOException
{
int bytesRead;
byte[] buffer;
FileInputStream input;
OutputStream output;
buffer = new byte[(int)file.length()];
input = new FileInputStream(file);
output = socket.getOutputStream();
bytesRead = input.read(buffer);
while(bytesRead > 0)
{
output.write(buffer,0,bytesRead);
bytesRead = input.read(buffer);
}
input.close();
output.close();
}
private void receiveFile(Socket socket, File file) throws IOException
{
int bytesRead;
byte[] buffer;
InputStream input;
FileOutputStream output;
buffer = new byte[(int)file.length()];
output = new FileOutputStream(file);
input = socket.getInputStream();
bytesRead = input.read(buffer);
while(bytesRead > 0)
{
output.write(buffer,0,bytesRead);
bytesRead = input.read(buffer);
}
input.close();
output.close();
}
I've already read up on Stack and everything I've tried hasn't fixed it. Does anyone have any ideas? Thanks!
Exact error is:
java.io.StreamCorruptedException: invalid stream header: 3C736372
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at Message.readMessageFrom(Message.java:32)
at Server$Handler.run(Server.java:220)
at java.lang.Thread.run(Thread.java:744)

Able to send images over socket but not text files

My client can send Images normally to server, but when it comes to text files they arrive empty. Any ideas what am I doing wrong? I'd really appreciate help, because I have been trying to make this work for many days now. Thanks.
Here is the server code:
class TheServer {
public void setUp() throws IOException { // this method is called from Main class.
ServerSocket serverSocket = new ServerSocket(1991);
System.out.println("Server setup and listening...");
Socket connection = serverSocket.accept();
System.out.println("Client connect");
System.out.println("Socket is closed = " + serverSocket.isClosed());
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = rd.readLine();
System.out.println("Recieved: " + str);
rd.close();
InputStream is = connection.getInputStream();
int bufferSize = connection.getReceiveBufferSize();
FileOutputStream fos = new FileOutputStream("C:/" + str);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
bos.flush();
bos.close();
is.close();
connection.close();
serverSocket.close();
}
}
and here is the client code:
public class TheClient {
public void send(File file) throws UnknownHostException, IOException { // this method is called from Main class.
Socket socket = null;
String host = "127.0.0.1";
socket = new Socket(host, 1991);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write(file.getName());
wr.newLine();
wr.flush();
byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
}
You are prematurely closing BufferedReader on server side before reading all the data. This essentially closes the connection.
You should not use Reader or Writer for non-character streams like binary image data. And you should not mix BufferedReader with any other stream wrapper for the same stream since it may read as many data as it fills in buffer.

ObjectInputStream giving strange results

Here is the code I am using.
Client:
public static void main(String[] args) throws IOException {
Socket socket = new Socket("0.0.0.0", 5555);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
FileInputStream in = new FileInputStream("C:/Documents and Settings/Owner/Desktop/Client/README.txt");
byte[] b = new byte[1024];
int i = 0;
i = in.read(b);
out.writeInt(i);
out.write(b, 0, i);
out.flush();
i = in.read(b);
out.writeInt(i);
out.write(b, 0, i);
out.flush();
out.close();
in.close();
socket.close();
}
Server:
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5555);
Socket s = ss.accept();
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
FileOutputStream fos = new FileOutputStream("C:/README.txt");
int i = 0;
i = in.readInt();
System.out.println(i);
byte[] bytes = new byte[i];
in.read(bytes);
i = in.readInt();
System.out.println(i);
byte[] bytes2 = new byte[i];
in.read(bytes2);
fos.write(bytes);
fos.close();
s.close();
ss.close();
}
The file README.txt has ~2400 bytes in it. When I run this, the server outputs this.
1024
1869488225
It then throws a java.lang.OutOfMemoryError.
Can anybody tell me why it is reading 1869488225 instead of 1024?
Thanks
in.read(bytes);
in.read(bytes2);
Here you are ignoring the return value of read and assuming that it fills the buffer. You should change read() to readFully() here, but in general you should never ignore a read() result. It can be -1 indicating EOS, or it can be any count from 1 up to the buffer size. If you inadvertently specify a zero length buffer it can even be zero.

Categories