Java - 每行中缺少第一个字母

我正在创建将文件传输到客户端的文件传输程序。但是当我传输文件时,它丢失了每一行的第一个字母。我的代码有什么问题?


我是 java 的新手,所以我不知道下一步该做什么。我试过更改字节大小但没有帮助。我应该怎么办?


Server.java


import java.io.*;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.Scanner;


class Server {

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

        FileInputStream fis = null;

        BufferedInputStream bis = null;

        OutputSteam os = null;

        ServerSocket serverSocket = null;

        Scanner scan = new Scanner(System.in);

        String fileSend;

        System.out.print("Type the path to the file to send >> ");

        fileSend = scan.nextLine();

        try {

            serverSocket = new ServerSocket(5467);

        } catch (Exception e) {

            System.out.println("Could not bind to port 5467, Maybe address is already is use or you need to run as administrator");

            return;

        }

        System.out.println("Listening on port 5467");

        System.out.println("Waiting for the connection...");

        while (true) {

            File FileSend = null;

            Socket socket = serverSocket.accept();

            OutputStream out = socket.getOutputStream();

            System.out.println("Accepted connection : " + socket);

            InputStream in = socket.getInputStream();

            DataInputStream dataIn = new DataInputStream(in);

            String login = dataIn.readUTF();

            String password = dataIn.readUTF();

            String result = "You credential is ";

            if (login.equals("1c18b5cdef8f9b4c5d6b2ad087265e597d1d4639337b73a04a335103c00ec64b") && password.equals("1c18b5cdef8f9b4c5d6b2ad087265e597d1d4639337b73a04a335103c00ec64b13d0b73358bfa8978dfaaf180565bcfecd3dc0631cda525920865145fb3fa131")) {

                result += "correct";

            } else {

                result += "incorrect";

            }

        }

    }


开心每一天1111
浏览 125回答 2
2回答

郎朗坤

文件是可序列化的,所以我建议您应该尝试直接通过 ObjectOutputStream / ObjectInputStream 发送它。例如在服务器端:ObjectInputStream in = new ObjectInputStream(socket.getInputStream());ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());...out.writeObject(yourFileObject);在客户端:ObjectInputStream in = new ObjectInputStream(socket.getInputStream());ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());...File receivedFile = null;try {    receivedFile = (File) in.readObject();}catch (IOException e) {...}

眼眸繁星

我不完全确定为什么会发生这种情况,但您不应该使用DataInputStreamwhich “让应用程序读取原始 Java 数据类型”,而InputStreamReaderwhich “是从字节流到字符流的桥梁”。此外,您可以将该阅读器包装成一个BufferedReader让您逐行阅读的内容,您最终会得到类似try (BufferedReader reader=new BufferedReader(new InputStreamReader(inStream, UTF8));     PrintWriter writer = new PrintWriter(file)) {    reader.lines().forEach(writer::println);}上传,或try (PrintWriter writer = new PrintWriter(outStream)) {    Files.lines().forEach(writer::println);}下载。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java