FileNotFound Exception in FileOutputStream - java

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.

Related

Exception in thread "main" java.net.SocketException: Connection reset -

I have created a simple Client/Server program where the client takes a file from command line arguments. The client then sends the file to the server, where it is compressed with GZIP and sent back to the client.
The server program when ran first is fine, and produces no errors but after running the client I get the error.
I am getting an error saying the connection is reset, and i've tried numerous different ports so i'm wondering if there is something wrong with my code or time at which i've closed the streams?
Any help would be greatly appreciated!
EDIT - Made changes to both programs.
Client:
import java.io.*;
import java.net.*;
//JZip Client
public class NetZip {
//Declaring private variables.
private Socket socket = null;
private static String fileName = null;
private File file = null;
private File newFile = null;
private DataInputStream fileIn = null;
private DataInputStream dataIn = null;
private DataOutputStream dataOut = null;
private DataOutputStream fileOut = null;
public static void main(String[] args) throws IOException {
try {
fileName = args[0];
}
catch (ArrayIndexOutOfBoundsException error) {
System.out.println("Please Enter a Filename!");
}
NetZip x = new NetZip();
x.toServer();
x.fromServer();
}
public void toServer() throws IOException{
while (true){
//Creating socket
socket = new Socket("localhost", 4567);
file = new File(fileName);
//Creating stream to read from file.
fileIn = new DataInputStream(
new BufferedInputStream(
new FileInputStream(
file)));
//Creating stream to write to socket.
dataOut = new DataOutputStream(
new BufferedOutputStream(
socket.getOutputStream()));
byte[] buffer = new byte[1024];
int len;
//While there is data to be read, write to socket.
while((len = fileIn.read(buffer)) != -1){
try{
System.out.println("Attempting to Write " + file
+ "to server.");
dataOut.write(buffer, 0, len);
}
catch(IOException e){
System.out.println("Cannot Write File!");
}
}
fileIn.close();
dataOut.flush();
dataOut.close();
}
}
//Read data from the serversocket, and write to new .gz file.
public void fromServer() throws IOException{
dataIn = new DataInputStream(
new BufferedInputStream(
socket.getInputStream()));
fileOut = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(
newFile)));
byte[] buffer = new byte[1024];
int len;
while((len = dataIn.read(buffer)) != -1){
try {
System.out.println("Attempting to retrieve file..");
fileOut.write(buffer, 0, len);
newFile = new File(file +".gz");
}
catch (IOException e ){
System.out.println("Cannot Recieve File");
}
}
dataIn.close();
fileOut.flush();
fileOut.close();
socket.close();
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.zip.GZIPOutputStream;
//JZip Server
public class ZipServer {
private ServerSocket serverSock = null;
private Socket socket = null;
private DataOutputStream zipOut = null;
private DataInputStream dataIn = null;
public void zipOut() throws IOException {
//Creating server socket, and accepting from other sockets.
try{
serverSock = new ServerSocket(4567);
socket = serverSock.accept();
}
catch(IOException error){
System.out.println("Error! Cannot create socket on port");
}
//Reading Data from socket
dataIn = new DataInputStream(
new BufferedInputStream(
socket.getInputStream()));
//Creating output stream.
zipOut= new DataOutputStream(
new BufferedOutputStream(
new GZIPOutputStream(
socket.getOutputStream())));
byte[] buffer = new byte[1024];
int len;
//While there is data to be read, write to socket.
while((len = dataIn.read(buffer)) != -1){
System.out.println("Attempting to Compress " + dataIn
+ "and send to client");
zipOut.write(buffer, 0, len);
}
dataIn.close();
zipOut.flush();
zipOut.close();
serverSock.close();
socket.close();
}
public static void main(String[] args) throws IOException{
ZipServer run = new ZipServer();
run.zipOut();
}
}
Error Message:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
at java.io.DataInputStream.read(DataInputStream.java:100)
at ZipServer.<init>(ZipServer.java:38)
at ZipServer.main(ZipServer.java:49)
First, the error occurs because the client fails and ends before sending any data, so that
the connection is closed at the time the server wants to read.
The error occurs because you assign the File objects to unused local variables (did your compiler not warn?)
public File file = null;
public File newFile = null;
public static void main(String[] args) throws IOException {
try {
String fileName = args[0];
File file = new File(fileName);
File newFile = new File(file +".gz");
}
catch (ArrayIndexOutOfBoundsException error) {
System.out.println("Please Enter a Filename!");
}
but In your toServer method you use the class variable file as parameter for FileInputStream and this variable is null and this results in an error which ends the program.
Second, if you finished the writing to the outputstream, you should call
socket.shtdownOutput();
Otherwise, the server tries to read until a timeout occurs.
Problem is that server is not able to download apache maven.
So what you can do is just copy the apache maven folder and paste it in the wrapper folder inside the project.
It will manually download the apache maven, and it will definitely work.

Java: Transfer a file from server to client and from client to server

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();
}
}
}

Image file not fully copied

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

transfer String and file through socket

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?

File sending from multiple client to Single server in Java Socket Programming

hi i am trying to create a program in java for sending files from multiple client to single server. is this is possible?
i tried this could for multiple client and single server and also it is from server to client sending program.
Client Program
public class Client {
public Client(String ip,String path,int i) throws IOException {
int filesize=2022386;
int bytesRead;
int currentTot = 0;
File file=new File(path);
File dir=new File("c:/PAMR/Dest"+i+"/");
String name=file.getName();
if(!dir.exists())
{
dir.mkdir();
}
Socket socket = new Socket(ip,9100);
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(dir+"/"+name);
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();
}
}
for Server
public class Source {
public Source(String path) throws IOException {
ServerSocket serverSocket = new ServerSocket(9100);
System.out.println("Server is in Listening Mode");
Socket socket = serverSocket.accept();
File transferFile = new File (path);
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();
os.write(bytearray,0,bytearray.length);
bin.close();
os.close();
os.flush();
socket.close();
serverSocket.close();
}
}
it is a part of code for my project i am doing.
Any body pls help.
You want something like this:
boolean working = true;
ServerSocket ss = new ServerSocket(9100);
while(working) {
Socket s = ss.accept();
MyThread myThread = new MyThread(s);
myTread.start();
}
where MyThread is a class of yours that extends the Thread class, accepts the connection to the client that just connected and then accepts any file or data sent to it.

Categories

Resources