r/javahelp • • Jul 25 '20

Can you review my code?

I recently created a program that could get information from a client, a name and some text, and then put that into a text file. From there the user can get open the text file straight from the program. I made it in two days. Please give me some tips in ways I can improve it, thank you!

The Server:

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.FileChannel;
import java.nio.file.*;

public class Server {
static boolean isAvailable = false;

public static void main(String[] args) throws IOException {

    // Get both connections to the client
    ServerSocket serverSocket =
            new ServerSocket(4999);
    ServerSocket serverSocket2 =
            new ServerSocket(4998);
    Socket socket =
            serverSocket.accept();
    Socket socket2 =
            serverSocket2.accept();

    // Confirm client connection
    System.out.println("The client has been connected to the server");

    // Get the streams from the client containing the string
    InputStreamReader fileNameIn =
            new InputStreamReader(socket.getInputStream());
    BufferedReader br =
            new BufferedReader(fileNameIn);

    InputStreamReader informationIn =
            new InputStreamReader(socket2.getInputStream());
    BufferedReader br2 =
            new BufferedReader(informationIn);

    // Read and assign the strings
    String fileName =
            br.readLine();
    String fileInformation =
            br2.readLine();

    // Get char array to write to the created file
    char[] fileInformationC =
            fileInformation.toCharArray();

    // Create file and write to it
    try (FileChannel fileChannel =
                 (FileChannel) Files.newByteChannel(
                         Path.of("C:\\Users\\Emman\\" + fileName + ".txt"),
                         StandardOpenOption.CREATE,
                         StandardOpenOption.WRITE
                 )) {

        int allocatedVal = 1000;

        ByteBuffer byteBuffer =
                ByteBuffer.allocate(allocatedVal);


        for (char c : fileInformationC){
            byteBuffer.put((byte) c);

            // Error handling: it is now impossible for the Buffer to run out of space
            // However a BufferOverflowException is caught, in case of a problem
            if (!(byteBuffer.position() == allocatedVal)){
                ByteBuffer.allocate(allocatedVal * 2);
            }
        }

        byteBuffer.rewind();

        fileChannel.write(byteBuffer);

        System.out.println("File has been created and written to, \n" +
                "Press Enter to open file");

        // The input does not matter
        //noinspection ResultOfMethodCallIgnored
        System.in.read();
        ProcessBuilder processBuilder =
                new ProcessBuilder("notepad.exe", "C:\\Users\\Emman\\" + fileName + ".txt");
        processBuilder.start();
    } catch (InvalidPathException e) {
        isAvailable = true;
        PrintWriter printToClient =
                new PrintWriter(socket.getOutputStream());

        printToClient.write("\"Error in creating/writing to file \\n\" +\n" +
                "Due to incorrect/invalid path\" +\n" +
                "e");
        printToClient.close();
    } catch (IOException e) {
        isAvailable = true;
        PrintWriter printToClient =
                new PrintWriter(socket.getOutputStream());

        printToClient.write("Error in creating/writing to file \n" +
                "Due to error in IO" +
                e);
        printToClient.close();

    } catch (BufferOverflowException e) {
        isAvailable = true;
        PrintWriter printToClient =
                new PrintWriter(socket.getOutputStream());

        printToClient.write("Error in creating/writing to file \n" +
                "Due to a buffer overflow" +
                e);
        printToClient.close();
    }

}
}

The Client:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
public static void main(String[] args) throws IOException{

    // Create connections to server
    Socket socket =
            new Socket("localhost", 4999);
    Socket socket2 =
            new Socket("localhost", 4998);
    // Create print writer output stream to give to server
    PrintWriter pr =
            new PrintWriter(socket.getOutputStream());
    PrintWriter pr2 =
            new PrintWriter(socket2.getOutputStream());

    // Create a buffered reader for reading the file name and information
    BufferedReader br =
            new BufferedReader(
                    new InputStreamReader(
                            System.in
                    )
            );

    // Get the file names and information
    String fileName = br.readLine();

    String information = br.readLine();

    // Put in the file Name and the file information
    pr.write(fileName);
    pr.close();

    pr2.write(information);
    pr2.close();

    // Checking whether the error message is available,
    // if not only one line of code is read, wasting barely any time
    if(Server.isAvailable){
        InputStreamReader errorInfoIn =
                new InputStreamReader(socket.getInputStream());
        BufferedReader readErrorInfo =
                new BufferedReader(errorInfoIn);

        String errorInfo =
                readErrorInfo.readLine();
        System.out.println(errorInfo);
        errorInfoIn.close();
    }
}
}
0 Upvotes

7 comments sorted by

5

u/aqua_regis Jul 25 '20

First off: methods

Keeping everything in main is an absolute anti-pattern. You can even reuse code between your two classes when you properly split everything.

Second: when you want help, be elaborate. You just describe coarsely what you made, but no reasoning why and what your use cases are.

In the meanwhile we know that you are a teenager in the fairly early stages of learning, but you have an insufferable attitude. You are dealing with adults here and you should work on your approach here.

1

u/[deleted] Jul 25 '20

well i just wanted people to look at my code and tell me what I did wrong. and it was just a refresher on Sockets tbh

3

u/DasBrain Jul 25 '20

What is the use case?

0

u/[deleted] Jul 25 '20

wdym?

2

u/DasBrain Jul 25 '20

The problem this program should solve.

I still don't know what those programs should solve, so judgement is hard (please describe how it should be used).

Server

The server creates two sockets to communicate with one client - strange, but not unheard of.

The server then uses FileChannels to write the file to a (partially) hard coded path. (hard coded == not portable - that path doesn't exist on my machine) To do this, it uses a ByteBuffer with a fixed size of 1000. (Common buffer sizes are powers of 2, so 1,2,4,8,16,32,64,128,256,512,1024...)
Then a byte is written to the byte buffer - by truncating a char to a byte - use a proper encoding here.
If the buffer gets full, a new buffer is allocated - and then never used. The next write will fail.

I don't get why you don't use Files.writeString() instead.

The server runs exactly once - then terminates.
That is... probably less useful. But I don't know your use case, so it might be perfectly useful there.

Before it terminates, it asks for user input - and will execute notepad.

Client

Connects to localhost. Hard coded, so no network use. Whatever, I'm sure your use case doesn't need that.

It then asks for two lines on stdin, first line is the file name, the second is the contents.

After it writes that info to both sockets it checks whether Server.isAvailable is true. It never is, and will never be - after all, the server runs in a different process - that's the point of using sockets - otherwise there is a cheaper and easier solution: memory.

Also the comment // if not only one line of code is read, wasting barely any time doesn't make any sense.
What time should be wasted? This is an interactive program, and you don't read several MB of data where this would be noticeable.

Summary

I can't see a use for it.

  • It's not used to transfer a file from one machine to an other (could have it's uses - but how to you get the program on the other machine - chicken and egg).

  • Yes, you can write ONE file from an other process - but why? (Also, it would garble the output for anything not ascii.)

  • Neither server nor client are background tasks - both require user interaction - and they have to run on the same machine. And I suppose there is one person sitting on that machine - who has to control both server and client. Why don't combine it into one thing?

In all, it's useless. Maybe a good exercise to learn about sockets.

0

u/[deleted] Jul 25 '20

yeah its just a small project I set myself to tysm

2

u/sinistergroupon Jul 25 '20

You used try with resources once correctly. You have a lot more streams, sockets, writers. They all need to be closed on success and failure. I.e. a lot more try with resources needed.

Why is allocatedVal not a static variable? Best I can tell it’s never changed.

The path to the file you’re producing is hard coded to your PC. It also hard codes the Windows slashes instead of using File.separator.

I need a coffee before I look at this more.

Import just the things you need not *. Any half decent IDE will do this for you.

Edit: same as someone else mentioned. The main method is bloated.