i would like to transfer file from server to client. before that i want to send file names from specific directory. the file is not transferring as the read is returning -1. can any one correct me where i am going wrong?
My client code goes like this.
import java.io.*;
import java.net.*;
class PC1Client {
public static void main(String args[]) throws UnknownHostException, IOException
{
byte[] aByte = new byte[1];
int bytesRead;
Socket sock = new Socket("localhost",3000);
InputStream is1 = sock.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is1));
String st = br.readLine();
System.out.println(st);
InputStream is = sock.getInputStream();
FileOutputStream fos = null;
fos = new FileOutputStream("F:\\ANI1.TXT");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
System.out.println(bytesRead);
do {
System.out.println("s");
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
sock.close();
}
}
My server code goes like this.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class PC1Server {
public static void main(String[] args) throws IOException
{
ServerSocket serversocket = new ServerSocket(3000);
try
{
while(true)
{
String str="";
Socket socket = serversocket.accept();
File file = new File("D:\\ani");
for(File fi : file.listFiles() )
{
str=str+fi.getName()+";";
}
PrintWriter outname = new PrintWriter(socket.getOutputStream());
outname.println(str);
outname.flush();
outname.close();
System.out.println("hello der");
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream() );
File myfile = new File("d:/hello.txt");
byte[] mybyte = new byte[(int)myfile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myfile));
bis.read(mybyte, 0, mybyte.length);
out.write(mybyte, 0, mybyte.length);
out.flush();
out.close();
}
}
catch(Exception e)
{
}
}
}
Few notes:
byte[] aByte = new byte[1]; is pointless - it forces you to read the file 1 byte at a time.
InputStream is = sock.getInputStream(); what is the point of opening the same input stream second time?
outname.close(); in your server code is what causes your problem.
Why do you close your output stream just to reopen it again?
Related
I am trying to send multiple files from client to server. Files are sent successfully but problem is that when I try to open the receiving file from targetFolder it seems files are corrupted.
Why this type of problem occurring and what is the solution?
How can I solve this by modifying the code to get uncorrupted files?
Server Code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
public class Server {
public final static String dirPath = "E:\\targetFolder\\";
public static void main(String[] args){
try{
ServerSocket servsock = new ServerSocket(8080);
Socket socket = servsock.accept();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
int filesCount = dis.readInt();
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++) {
long fileLength = dis.readLong();
String fileName = dis.readUTF();
files[i] = new File(dirPath + fileName);
FileOutputStream fos = new FileOutputStream(files[i]);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] byteArr = new byte[(int)fileLength];
for (int j = 0; j < fileLength; j++) {
int b = bis.read();
bos.write(b);
byteArr[j] = (byte) b;
}
// CheckSum calculating
System.out.println("============================");
System.out.println("File Name: "+fileName);
Checksum checksum = new Adler32();
checksum.update(byteArr,0, byteArr.length);
System.out.println("Check Sum: "+checksum.getValue());
System.out.println("============================");
}
dis.close();
}catch(Exception e){
System.out.println(e);
}
}
}
Client Code:
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
public class Client {
private static String directory = "E:\\sourceFolder";
public static void main(String[] args) {
try{
Socket sock=new Socket("localhost",8080);
System.out.println("Connecting...");
BufferedOutputStream bos = new BufferedOutputStream(
sock.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
File[] files = new File(directory).listFiles();
dos.writeInt(files.length);
for(File file: files) {
long length = file.length();
dos.writeLong(length);
String fileName = file.getName();
dos.writeUTF(fileName);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int bt = 0;
byte[] byteArr = new byte[(int)length];
int i = 0;
while((bt = bis.read()) != -1) {
bos.write(bt);
byteArr[i++] = (byte) bt;
}
// CheckSum calculating
System.out.println("============================");
System.out.println("File Name: "+fileName);
Checksum checksum = new Adler32();
checksum.update(byteArr,0, byteArr.length);
System.out.println("Check Sum: "+checksum.getValue());
System.out.println("============================");
bis.close();
}
dos.close();
}catch(Exception e){
System.out.println(e);
}
}
}
I'm getting error of FileNotFound. Basically, I'm trying to upload file from client to server.
Please, help me with it.
This is client.java class
package ftppackage;
import java.net.*;
import java.io.*;
public class Client {
public static void main (String [] args ) throws IOException {
Socket socket = new Socket("127.0.0.1",15123);
File transferFile = new File ("D:\\AsiaAd.wmv");
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files...");
os.write(bytearray,0,bytearray.length);
os.flush();
socket.close();
System.out.println("File transfer complete");
}
}
And this is my server.java class
package ftppackage;
import java.net.*;
import java.io.*;
public class Server {
public static void main (String [] args ) throws IOException {
int filesize=1022386;
int bytesRead;
int currentTot = 0;
ServerSocket serverSocket = new ServerSocket(15123);
Socket socket = serverSocket.accept();
System.out.println("Accepted connection : " + socket);
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("E:\\0\\"); // it is creating new file not copying the one from client
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;
do {
bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0)
currentTot += bytesRead;
} while(bytesRead > -1);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
socket.close();
}
}
Plus, guide me how do add progress bar in it with percentage. I read about SwingWorker here but unable to implement it as I'm totally new with threading concepts.
Thank you for considering my questions.
FileNotFoundException is something you will get if you point the File Object to some File which is not existing in that path. it means what ever the file you are trying to upload in not there in the specified path. SO make sure you give a valid path.
I am a newbie and I want to accomplish file transfer from server to client "do something with it" and then send the file back to the server. The most basic code I am using is here:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException {
ServerSocket servsock = new ServerSocket(123456);
File myFile = new File("s.pdf");
while (true) {
Socket sock = servsock.accept();
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
}
}
}
The client module
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class Main {
public static void main(String[] argv) throws Exception {
Socket sock = new Socket("127.0.0.1", 123456);
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("s.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
}
}
Got it from this website: http://www.java2s.com/Code/Java/Network-Protocol/TransferafileviaSocket.htm
I understand how this works but I don't know how to send a file back to the server.
Please help.
I've written a file transfer class in the past, you can use it both in your client and server (by making an instance) and use the methods to send and receive files as much as you want.
import java.io.*;
import java.net.Socket;
public class FileTransferProcessor {
Socket socket;
InputStream is;
FileOutputStream fos;
BufferedOutputStream bos;
int bufferSize;
FileTransferProcessor(Socket client) {
socket = client;
is = null;
fos = null;
bos = null;
bufferSize = 0;
}
void receiveFile(String fileName) {
try {
is = socket.getInputStream();
bufferSize = socket.getReceiveBufferSize();
System.out.println("Buffer size: " + bufferSize);
fos = new FileOutputStream(fileName);
bos = new BufferedOutputStream(fos);
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) >= 0) {
bos.write(bytes, 0, count);
}
bos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
void sendFile(File file) {
FileInputStream fis;
BufferedInputStream bis;
BufferedOutputStream out;
byte[] buffer = new byte[8192];
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
out = new BufferedOutputStream(socket.getOutputStream());
int count;
while ((count = bis.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.close();
fis.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am using following program to get file from server:
public static void main(String[] argv) throws Exception {
Socket sock = new Socket("127.0.0.1", 12345);
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("E://cy.jpg");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
}
This is creating the file but only a few contents of the image are being copied.
Can someone please explain what is wrong with this code and how to fix it?
You are reading only 1024 bytes from InputStream. You need wrap reading by while loop:
int bytesRead ;
while ((bytesRead = is.read(mybytearray)) != -1) {
bos.write(mybytearray, 0, bytesRead);
}
Try this one.
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
import org.apache.commons.io.IOUtils;
public class Test
{
public static void main(String[] argv) throws Exception {
Socket sock = new Socket("127.0.0.1", 12345);
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("E://cy.jpg");
IOUtils.copy(is, fos);
IOUtils.closeQuietly(fos);
sock.close();
}
}
This code uses IOUtils from Commons IO
In my TCP socket program I have to send data from client to server. In server side I have to read the streams and write it in file. But File is created and nothing is written inside.
Client side coding to send file:
try
{
Socket ss = new Socket("localhost", 5010);
BufferedOutputStream put = new BufferedOutputStream(ss.getOutputStream());
BufferedReader st = new BufferedReader(new InputStreamReader(ss.getInputStream()));
File f = new File("e://read.txt");
FileInputStream fis = new FileInputStream(f);
byte buf[] = new byte[1024];
int read;
while((read = fis.read(buf, 0, 1024)) != -1)
{
put.write(buf,0,read);
put.flush();
}
//d.close();
System.out.println("File transfered");
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
Server to read the inputstream and write it in a file:
try
{
ServerSocket ss = new ServerSocket(5010);
Socket s = ss.accept();
BufferedReader get = new BufferedReader(new InputStreamReader(s.getInputStream()));
FileWriter writedata = new FileWriter("c://write.txt");
BufferedWriter bw = new BufferedWriter(writedata);
String line=bw.toString();
while ((line = get.readLine()) != null) {
bw.write(line + "\n");
}
}
catch(Exception e)
{
System.out.println(e);
}
What is the problem?
You forgot bw.close and bw.flush....below is the code that works...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer
{
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(5010);
Socket s=ss.accept();
BufferedReader get= new BufferedReader(new InputStreamReader(s.getInputStream()));
FileWriter writedata=new FileWriter("c://Test//testoutput.txt");
BufferedWriter bw=new BufferedWriter(writedata);
String line=bw.toString();
while ((line = get.readLine()) != null) {
bw.write(line + "\n");
}
bw.flush();
bw.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class TestClient
{
public static void main(String[] args)
{
try
{
Socket ss=new Socket("localhost",5010);
BufferedOutputStream put=new BufferedOutputStream(ss.getOutputStream());
BufferedReader st=new BufferedReader(new InputStreamReader(ss.getInputStream()));
File f=new File("c://Test//testinput.txt");
FileInputStream fis=new FileInputStream(f);
byte buf[]=new byte[1024];
int read;
while((read=fis.read(buf,0,1024))!=-1)
{
put.write(buf,0,read);
put.flush();
}
//d.close();
System.out.println("File transfered");
ss.close();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Don't use Readers and Writers unless you know that the data is text. Use InputStreams and OutputStreams, and copy them so:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
out.close();
in.close();
Use this logic in both the client and the server.
Notes:
It is counterproductive to put a flush() inside that loop.
If buffer is greater than 4096, which it should be, it is pointless to use a BufferedInputStream.