当前位置: 首页 > 知识库问答 >
问题:

如何从字符中清除套接字流,以便将其用于字节(字节文件传输)?

戚奇略
2023-03-14

我正在尝试制作一些包含文件传输的程序。当然,我必须使用字符流进行一些客户机-服务器通信,我还需要使用字节流来传输文件。当我从BufferedReader中使用println方法form PrintWriter和readLine时会出现问题,因为readLine读取行,但在流中留下“\n”,这会在我尝试使用字节流传输文件后导致问题(我不能100%确定这就是问题)。所以我需要摆脱这个角色,我尝试使用Reader类中的read方法,但没有成功。代码在不使用字符拖缆的情况下可以完美工作。请注意readLine的调用对sizeOfFile的影响。

服务器

import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private static int SERVER_PORT = 9999;
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(SERVER_PORT);
            System.out.println("Server je pokrenut");
            while (true) {
                Socket sock = ss.accept();
                new MultithreadServer(sock);
            }
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

服务器Thread

import java.io.*;
import java.net.Socket;
import java.util.*;

public class MultithreadServer extends Thread {
    private Socket sock;
    BufferedReader inChar;
    PrintWriter outChar;
    BufferedInputStream in;
    BufferedOutputStream out;
    DataOutputStream outByte;
    public MultithreadServer(Socket sock) throws Exception {
        this.sock = sock;
        inChar = new BufferedReader(
            new InputStreamReader(sock.getInputStream()));
        outChar = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
            sock.getOutputStream())), true);
        in = new BufferedInputStream(sock.getInputStream());
        out = new BufferedOutputStream(sock.getOutputStream());
        outByte = new DataOutputStream(sock.getOutputStream());
        start();
    }
    public void run() {
        try {
            String request = inChar.readLine();
            System.out.println("Fajl: " + request);
            File file = new File(request);
            BufferedInputStream in = new BufferedInputStream(
                new FileInputStream(file));
            long sizeOfFile = (long) file.length();

            outChar.println("SOME_MESSAGE"); //PROBLEM

            byte[] buffer = new byte[4096];
            int len = 0;
            outByte.writeLong(sizeOfFile);
            long totalyTransfered = 0;
            while ((len = in.read(buffer, 0, buffer.length)) !=-1) {
                out.write(buffer, 0, len);
                totalyTransfered += len;
            }
            System.out.println("Total:" + totalyTransfered);
            out.flush();
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

客户

import java.util.*;
import java.net.*;
import java.io.*;

public class ClientServer {
 static int SERVER_PORT = 9999;
 public static void main(String[] args) throws Exception {
 InetAddress address = InetAddress.getByName("127.0.0.1");
 Socket sock = new Socket(address, SERVER_PORT);
  PrintWriter out = new PrintWriter(new BufferedWriter(
   new OutputStreamWriter(sock.getOutputStream())), true);
  BufferedReader inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
  Reader readChar = new InputStreamReader(sock.getInputStream());

 System.out.println("File:");   // choosing file from server
 Scanner consoleInput = new Scanner(System.in);
 String file = consoleInput.next();
 out.println(file);

 DataInputStream in = new DataInputStream(sock.getInputStream());

 System.out.println("Type name of file:");  //choosing name for file on client
 String newFile = consoleInput.next();

 OutputStream outByte = new FileOutputStream(newFile);
 byte[] buffer = new byte[4096];


 System.out.println("aa"+inChar.readLine()+"aa");   //PROBLEM
 System.out.println("SOME_TEXT"+readChar.read()+"SOME_TEXT");  //TRYING TO FIX THE  PROBLEM
   //       in.read(); in.read();                      // DIFFERENT TRY
   long sizeOfFile= in.readLong();                    // BUT IT STILL HAS INFLUENCE OF       sizeOfFile
 System.out.println("Size of file:" + sizeOfFile);

 long totalyTransfered= 0;
 int len = 0;
 while ((len = in.read(buffer,0,buffer.length)) != -1) {
  outByte.write(buffer, 0, len);
  System.out.println("In one pass:" + len);
  sizeOfFile-=len;
  totalyTransfered+=len;
 System.out.println("Total:" + totalyTransfered);
 if (sizeOfFile<=0)break; 
  }
   System.out.println("Available: "+in.available());
  outByte.flush();
  outByte.close();

}
}

共有1个答案

林弘文
2023-03-14

我修改了你的代码并成功传输了文件,很抱歉我没有时间解决你代码中的问题,我认为你的代码不简单:)。

但是请在下面找到你修改过的代码,它非常简单,我从这里引用了这段代码

class Server:
No changes

类ClientServer:

public class ClientServer {

    static int SERVER_PORT = 9999;

    private static final String fileOutput = "C:\\testout.pdf";

    public static void main(String[] args) throws Exception {
        InetAddress address = InetAddress.getByName("127.0.0.1");

        Socket sock = new Socket(address, SERVER_PORT);
        InputStream is = sock.getInputStream();
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(sock.getOutputStream())), true);
        BufferedReader inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        Reader readChar = new InputStreamReader(sock.getInputStream());

        System.out.println("File:");   // choosing file from server
        Scanner consoleInput = new Scanner(System.in);
        String file = consoleInput.next();
        out.println(file);

        DataInputStream in = new DataInputStream(sock.getInputStream());

        System.out.println("Type name of file:");  //choosing name for file on client
        //String newFile = consoleInput.next();
        //
        //      OutputStream outByte = new FileOutputStream(newFile);
        //      byte[] buffer = new byte[4096];
        //
        //
        //      System.out.println("aa"+inChar.readLine()+"aa");   //PROBLEM
        //      System.out.println("SOME_TEXT"+readChar.read()+"SOME_TEXT");  //TRYING TO FIX THE  PROBLEM
        //      //       in.read(); in.read();                      // DIFFERENT TRY
        //      long sizeOfFile= in.readLong();                    // BUT IT STILL HAS INFLUENCE OF       sizeOfFile
        //      System.out.println("Size of file:" + sizeOfFile);
        //
        //      long totalyTransfered= 0;
        //      int len = 0;
        //      while ((len = in.read(buffer,0,buffer.length)) != -1) {
        //          outByte.write(buffer, 0, len);
        //          System.out.println("In one pass:" + len);
        //          sizeOfFile-=len;
        //          totalyTransfered+=len;
        //          System.out.println("Total:" + totalyTransfered);
        //          if (sizeOfFile<=0)break; 
        //      }
        //      System.out.println("Available: "+in.available());
        //      outByte.flush();
        //      outByte.close();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        int bytesRead;
        try {
            byte[] aByte = new byte[1];
            fos = new FileOutputStream(fileOutput);
            bos = new BufferedOutputStream(fos);

            bytesRead = is.read(aByte, 0, aByte.length);

            do {
                baos.write(aByte);
                bytesRead = is.read(aByte);
            } while (bytesRead != -1);

            bos.write(baos.toByteArray());
            bos.flush();
            bos.close();
            sock.close();
        } catch (IOException ex) {
            // Do exception handling
        }
    }
}

类MutithReadServer:

public class MultithreadServer extends Thread {

    private Socket sock;
    BufferedReader inChar;
    PrintWriter outChar;
    BufferedInputStream in;
    BufferedOutputStream out;
    DataOutputStream outByte;

    public MultithreadServer(Socket sock) throws Exception {
        this.sock = sock;
        inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        outChar = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
        in = new BufferedInputStream(sock.getInputStream());
        out = new BufferedOutputStream(sock.getOutputStream());
        outByte = new DataOutputStream(sock.getOutputStream());
        start();
    }

    public void run() {
        try {
            String request = inChar.readLine();
            System.out.println("Fajl: " + request);
            File file = new File(request);
            BufferedInputStream in = new BufferedInputStream(
                    new FileInputStream(file));

            byte[] buffer = new byte[(int) file.length()];

            FileInputStream fis = null;

            try {
                fis = new FileInputStream(file);
            } catch (FileNotFoundException ex) {
                // Do exception handling
            }
            BufferedInputStream bis = new BufferedInputStream(fis);
            //long sizeOfFile = (long) file.length();

            //outChar.println("SOME_MESSAGE"); //PROBLEM

            //byte[] buffer = new byte[4096];
            try {
                bis.read(buffer, 0, buffer.length);
                out.write(buffer, 0, buffer.length);
                out.flush();
                out.close();
                sock.close();

                // File sent, exit the main method
                return;
            } catch (IOException ex) {
                // Do exception handling
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注意:没有几行未使用的代码,请删除。希望它能在周日有所帮助:)!!!

 类似资料:
  • 如何将字符串(字节字符串)转换为字节(字节字符串),而不必手动复制和粘贴字符串并在其前面放置b?

  • 问题内容: 请解释什么是字节流和字符流。这些到底是什么意思?Microsoft Word文档是面向字节还是面向字符? 谢谢 问题答案: 流是顺序访问文件的一种方式。字节流逐字节访问文件。字节流适用于任何类型的文件,但不适用于文本文件。例如,如果文件使用unicode编码,并且一个字符用两个字节表示,则字节流将分别处理这些字节,您需要自己进行转换。 字符流将逐字符读取文件。必须为字符流提供文件的编码

  • 我在将JSON对象转换为字节时遇到了一个问题。我需要这样的东西: 我将感激任何帮助。提前道谢。

  • 我正在建立一个自定义的文件创建与Android应用程序。我试图将Bytebuffer的内容(它是我创建的自定义类中的字符串成员)写入字节类型的文件。但是,每当我这样做时,我得到的是字符串格式的文件内容。我尝试了几种替代方法,例如使用get方法、BufferedOutputStream类、ByteArrayOutputStream类、DataOutputStream类、Filechannel类等。以

  • 我有一个类,它接收用户发送的消息并在终端上打印出来,但现在我正在尝试编写一个类,从用户那里读取数据,将来自用户的字符串数据转换成字节数组,并将字节数组写入套接字。 我试图使用BufferedReader从用户读取数据,并使用OutputStream将字节数组写入套接字,但由于某些原因,我正在写入套接字的消息没有传递到服务器。 是一个与我发送到的服务器和端口号相同的套接字! 当我运行这个时没有错误,

  • Spring似乎无法将响应直接流式传输到文件,而不将其全部缓冲在内存中。使用较新的Spring 5实现这一点的正确方法是什么? 我看到人们在中找到了一些解决此问题的方法,但我更感兴趣的是使用以正确的方式解决此问题。 有许多使用下载二进制数据的示例,但几乎所有示例都将加载到内存中。