gpt4 book ai didi

java - 我应该使用哪个流在 java 中通过网络传输自定义文件(例如 jpeg 或 mp3)?

转载 作者:行者123 更新时间:2023-12-01 14:44:30 26 4
gpt4 key购买 nike

我尝试用java编写服务器和客户端来传输文件。但收到的文件很奇怪,看起来充满了奇怪的字节,并且不会用任何应用程序打开,但其大小与源文件完全相同。我不知道问题出在哪里!与编码有关吗?

服务器端:

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


public class MyServer {


public static void main(String[] args) {
char sp = File.separatorChar;
String home = System.getProperty("user.home");
try {
ServerSocket server = new ServerSocket(5776);
while (true){
Socket connection = server.accept();
try {
String FileName=home+sp+"33.jpg";
File inputFile = new File(FileName);
FileInputStream Fin = new FileInputStream(inputFile);
long fileLength = inputFile.length();
byte[] bt= new byte[(int) fileLength];
DataOutputStream Oout = new DataOutputStream(connection.getOutputStream());
Oout.writeLong(fileLength);
Oout.write(bt);
Oout.flush();
Oout.close();
connection.close();
} catch (IOException ex) {}
finally {
try {
if(connection!= null) connection.close();
} catch (IOException e) {}
}
}
} catch (IOException e) {

System.err.println("There is a server on port 5776");
}

}

}

客户端:

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

public class Client {


public static void main(String[] args) {
byte[] IP={(byte)192,(byte)168,1,7};
char sp = File.separatorChar;
String home = System.getProperty("user.home");
String SharingPathString = home+sp+"File Sharing";
String FileName = SharingPathString+sp+"file.jpg";
try {
InetAddress add = InetAddress.getByAddress(IP);
Socket theSocket= new Socket("Shayan-8",5776);
DataInputStream in= new DataInputStream(theSocket.getInputStream());
final long FileLength = in.readLong();
System.out.println("FileLength: "+FileLength);
File SharingPath = new File(SharingPathString);
if(!SharingPath.exists())
SharingPath.mkdir();
File outputFile = new File(FileName);
if(outputFile.exists())
outputFile.delete();
//outputFile.createNewFile();
FileOutputStream Fos = new FileOutputStream(FileName);
DataOutputStream dos = new DataOutputStream(Fos);
byte[] buffer = new byte[100];
int count=0;
long current=0;
while(current < FileLength && (count=in.read(buffer,0,(int)Math.min(FileLength-current, buffer.length)))!=-1)
{Fos.write(buffer, 0, count);
current+=count;
}
// while((count=in.read())!=-1)
// dos.write(count);
dos.close();
Fos.close();
} catch (UnknownHostException uhe) {
System.err.println(uhe);
} catch (IOException e) {
System.err.println(e);
}


}

}

最佳答案

您尚未在 bt[] 中读取任何内容。所以您正在写入正确数量的空字节。

关于java - 我应该使用哪个流在 java 中通过网络传输自定义文件(例如 jpeg 或 mp3)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15584338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com