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)
Related
I am working on reading a file and write same file, but the problem is the downloaded file is 2kb larger than input original file.
Some piece of code
#Override
public void run() {
try {
BufferedInputStream bis;
ArrayList<byte[]> al =new ArrayList<byte[]>();
File file = new File(Environment.getExternalStorageDirectory(), "test.mp3");
byte[] bytes = new byte[2048];
bis = new BufferedInputStream(new FileInputStream(file));
OutputStream os = socket.getOutputStream();
int read ;
int fileSize = (int) file.length();
int readlen=1024;
while (fileSize>0) {
if(fileSize<1024){
readlen=fileSize;
System.out.println("Hello.........");
}
bytes=new byte[readlen];
read = bis.read(bytes, 0, readlen);
fileSize-=read;
al.add(bytes);
}
ObjectOutputStream out1 = new ObjectOutputStream(new FileOutputStream(Environment.getExternalStorageDirectory()+"/newfile.mp3"));
for(int ii=1;ii<al.size();ii++){
out1.write(al.get(ii));
// out1.flush();
}
out1.close();
File file1 = new File(Environment.getExternalStorageDirectory(), "newfile.mp3");
Don't use an ObjectOutputStream. Just use the FileOutputStream, or a BufferedOutputStream wrapped around it.
The correct way to copy streams in Java is as follows:
byte[] buffer = new byte[8192]; // or more, or even less, anything > 0
int count;
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
out.close();
Note that you don't need a buffer the size of the input, and you don't need to read the entire input before writing any of the output.
Wish I had $1 for every time I've posted this.
I think you should use ByteArrayOutputStream not an ObjectOutputStream.
I belive this is not a raw code, but the parts of the code, placed in different procedures, otherwise it is meaningless.
For example, in case you want to stream some data from a file, process this data, and then write the data to another file.
BufferedInputStream bis = null;
ByteArrayOutputStream al = new ByteArrayOutputStream();
FileOutputStream out1 = null;
byte[] bytes;
try {
File file = new File("testfrom.mp3");
bis = new BufferedInputStream(new FileInputStream(file));
int fileSize = (int) file.length();
int readLen = 1024;
bytes = new byte[readLen];
while (fileSize > 0) {
if (fileSize < readLen) {
readLen = fileSize;
}
bis.read(bytes, 0, readLen);
al.write(bytes, 0, readLen);
fileSize -= readLen;
}
bis.close();
} catch (IOException e){
e.printStackTrace();
}
//proceed the data from al here
//...
//finish to proceed
try {
out1 = new FileOutputStream("testto.mp3");
al.writeTo(out1);
out1.close();
} catch (IOException e){
e.printStackTrace();
}
Don't forget to use try-catch directives where it needed
http://codeinventions.blogspot.ru/2014/08/creating-file-from-bytearrayoutputstrea.html
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();
}
}
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)
I'm trying to write the inputstream image to OutputStream to display the image in the browser this is the code:
try
{
InputStream input = Filer.readImage("images/test.jpg");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1)
{
responseBody.write(buffer, 0, bytesRead);
}
}
catch(IOException e)
{
System.out.println(e);
}
the readImage:
public static InputStream readImage(String file) throws IOException {
InputStream input = new FileInputStream(file);
return input;
}
This is the original image:
This is the output after the above procedure:
What is wrong with my code?
You need to close the output stream:
InputStream input = Filer.readImage("images/test.jpg");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
responseBody.write(buffer, 0, bytesRead);
}
responseBody.close(); // <-----------
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.