0% found this document useful (0 votes)
40 views2 pages

RecieveThreadfile PDF

This Java class defines a thread to receive a file over a socket connection. It initializes socket and stream variables, reads bytes from the input stream into a byte array, writes the bytes to a file output stream, and closes the streams upon completion or error.

Uploaded by

Utkarsh Kashyap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views2 pages

RecieveThreadfile PDF

This Java class defines a thread to receive a file over a socket connection. It initializes socket and stream variables, reads bytes from the input stream into a byte array, writes the bytes to a file output stream, and closes the streams upon completion or error.

Uploaded by

Utkarsh Kashyap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

package com.

company;
import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RecieveFile extends Thread{
private Socket socket;
private BufferedWriter bufferedWriter;
private int FILE_SIZE=6022386;
private String FILE_TO_RECEIVED = "Battery.txt";
private int bytesRead;
private int current = 0;
private FileOutputStream fos = null;
private BufferedOutputStream bos = null;
public RecieveFile(Socket socket){
this.socket=socket;
}
@Override
public void run() {
try {
this.bufferedWriter = new BufferedWriter(new FileWriter("Battery.txt",true));
this.bufferedWriter.write(this.socket.toString());
// receive file
byte[] mybytearray = new byte[FILE_SIZE];
InputStream is = socket.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length - current));
if (bytesRead >= 0) current += bytesRead;
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)" + " from " +
socket.toString());
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/*if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
if (bufferedWriter!=null) {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

You might also like