Java - copy/paste file from client to server getting error - UTF-8 encoding problem opening file

Pachuca :

I recently tried to create a copy/paste app with Java using this answer and I didn't change much other than directories of the file. I created a regular text file with "test" written inside it. When I run the app it copies the file, but gives me an error about utf-8 encoding in success_test.txt and I'm not sure how to fix this or what's causing the problem. I'm running this on Ubuntu 18.04 in Intellij Ultimate 2019.2

here's the server and the client is pretty much the same as in the answer

Server:

public class Server extends Thread {

public static final int PORT = 3332;
public static final int BUFFER_SIZE = 626;

@Override
public void run() {
    try {
        ServerSocket serverSocket = new ServerSocket(PORT);
        while (true) {
            Socket s = serverSocket.accept();
            saveFile(s);
        }
    } catch (Exception e) {
    }
}

private void saveFile(Socket socket) throws Exception {
    InputStream inputStream = socket.getInputStream();
    FileOutputStream fileOutputStream = new FileOutputStream("/home/user/Documents/success_test.txt");;

    byte[] byteArray = new byte[1024];
    System.out.println("Reading file from server...");
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
    int bytesRead;
    while ((bytesRead = inputStream.read(byteArray)) != -1) {
        bufferedOutputStream.write(byteArray);
    }

    bufferedOutputStream.close();
    System.out.println("Writing file complete...");

}

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

}

when I try to open success_test.txt this is what I see

https://imgur.com/a/3rpvkiJ

UTF-8 error

Nick :

You are reading your data into a 1024 byte long array, then writing that to a file. This means your output file is padded to 1024 bytes with \00 which is the NULL character.

You have your bytesRead variable, so you should use it to only write that many bytes:

bufferedOutputStream.write(byteArray, 0, bytesRead);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326671&siteId=1