0

Guide me through this exception. I have been trying to send a file from client to server - where in client enters the name of the file manually. But i am getting NullPointerException on client side - the possible error as of I know is "before opening the file, I am passing a null argument hence the NPE"

Server.java

import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends Thread {
    public static final int PORT = 3333;
    public static final int BUFFER_SIZE = 100;

    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);

            while (true) {
                Socket s = serverSocket.accept();
                saveFile(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveFile(Socket socket) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        FileOutputStream fos = null;
        byte [] buffer = new byte[BUFFER_SIZE];

        // 1. Read file name.
        Object o = ois.readObject();

        if (o instanceof String) {
            fos = new FileOutputStream(o.toString());
        } else {
            throwException("Something is wrong");
        }

        // 2. Read file to the end.
        Integer bytesRead = 0;

        do {
            o = ois.readObject();

            if (!(o instanceof Integer)) {
                throwException("Something is wrong");
            }

            bytesRead = (Integer)o;

            o = ois.readObject();

            if (!(o instanceof byte[])) {
                throwException("Something is wrong");
            }

            buffer = (byte[])o;

            // 3. Write data to output file.
            fos.write(buffer, 0, bytesRead);
        } while (bytesRead == BUFFER_SIZE);

        fos.close();

        ois.close();
        oos.close();
    }

    public static void throwException(String message) throws Exception {
        throw new Exception(message);
    }

    public static void main(String[] args) {
        new Server().start();
    }
}  

Client.java

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.lang.*;

public class Client {
    public static void main(String[] args) throws Exception {
        String fileName = null;

       try {
            fileName = args[0];
        } catch (Exception e) {
            System.out.println("Enter the name of the file :");
        }
        File file = new File(fileName);
        Socket socket = new Socket("localhost", 3333);
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

        oos.writeObject(file.getName());

        FileInputStream fis = new FileInputStream(file);
        byte [] buffer = new byte[Server.BUFFER_SIZE];
        Integer bytesRead = 0;

        while ((bytesRead = fis.read(buffer)) > 0) {
            oos.writeObject(bytesRead);
            oos.writeObject(Arrays.copyOf(buffer, buffer.length));
        }

        oos.close();
        ois.close();
    }
}  
highlander141
  • 1,683
  • 3
  • 23
  • 48
  • Does `args[0]` contain the name of the `File`? Moreover, you need to give the entire path, not just the file name in the constructor call, unless the file you are working with is in the current working directory. – Kazekage Gaara Aug 20 '12 at 09:54
  • 2
    If `fileName = args[0]` throws an exception, you just print out some text to `System.out` saying "Enter the name of the file: " but you *never actually get any input*. You basically swallow that exception and do nothing with it, then proceed to execute the rest of your code with `fileName` being `null`. – Anthony Grist Aug 20 '12 at 09:56
  • @Anthony Grist The exception I am getting is at the File class i.e at line:18 in my Client -> File file = new File(fileName);. – highlander141 Aug 20 '12 at 10:06
  • 1
    @highlander141 That's exactly my point - it's entirely possible that, with your code, that line will execute with `fileName` being `null`, therefore passing `null` to the File constructor. – Anthony Grist Aug 20 '12 at 10:10
  • Try to print the Stack Tracce of the Exception.Then check where is the Null argument. – PrasoonMishra Aug 20 '12 at 09:59

3 Answers3

2
String fileName = null;

       try {
            fileName = args[0];
        } catch (Exception e) {
            System.out.println("Enter the name of the file :");
        }
        File file = new File(fileName);

The above code simply checks if the user has provided a file name or not. Even if the user doesn't enter any file name, it proceeds further, as a result null is being passed on as the argument to File constructor. And hence your NPE.

Put the File instantiation inside a try catch block as well. And secondly, the File constructor takes in the entire path of the file as a parameter, so ensure that the file you are working with is in the current working directory.

Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
  • Thank you, your suggestion worked. But when the client is a different machine, what is the situation ? Can you guide me ? – highlander141 Aug 20 '12 at 10:43
  • If the `File` exists on the client machine, it would be better to explicitly ask for the entire path from the client, instead of assuming that the file will exist in the current working directory. – Kazekage Gaara Aug 20 '12 at 10:48
  • Help needed again ... on server side - if we want to store the files in a specified directory ? please guide me through this ... – highlander141 Aug 23 '12 at 09:15
  • 1
    @highlander141 [This](http://stackoverflow.com/questions/4687615/how-to-achieve-transfer-file-between-client-and-server-using-java-socket) is probably all that you need to guide yourself. :-) – Kazekage Gaara Aug 23 '12 at 15:15
1

Your code

String fileName = null


try {
    fileName = args[0];
 } catch (Exception e) {
    System.out.println("Enter the name of the file :");
 }

has got a problem. Suppose if the user has not typed the file name, it ignores the exception saying "Enter the name of the file :" . So your fileName will be NULL always.

Either you try modify it as

try {
    fileName = args[0];
 } catch (Exception e) {
    System.out.println("Usage: java Client <file_name>");
    System.exit(0);
 }

or

try {
 fileName = args[0];
} catch (Exception e) {
  System.out.println("Enter the name of the file :");
  Scanner scanner = new Scanner(System.in);
  String file_name = scanner.nextLine();
}

And whatever the method you are going to use , check for the NULL like

if (fileName == null) {
  System.out.println("File name can not be NULL");
  System.exit(0);
}

This should do. Cheers.

sakthisundar
  • 3,278
  • 3
  • 16
  • 29
1

1. First of all its better to use Scanner for taking the path along with the trim() method, so to prevent any accidental addition of space in the path.

Scanner scan = new Scanner(System.in);
String tmppath = scan.nextLine();
String path = tmppath.trim();

2. But still if you want to go your way...... then try this..

File f = null;   // If its in class scope, then 
                 // no need to initialize it to null, bydefault it will be null.

 try{

     f = args[0];


 }catch(Exception ex){

     System.out.println("file object is null");
}
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75