我製作了一個應該讓客戶端讀取文件的服務器。總而言之,它正在工作,但有些字節,例如HEX 9D正在轉向HEX 3F。我沒有更多的想法,也沒有在網上找到任何東西。我的服務器代碼:Java:字節傳輸不正確
package de;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class UpdateThread extends Thread {
public UpdateThread(Socket s) {
socket = s;
}
public void run() {
try {
execute();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("resource")
public void execute() throws IOException {
if (UpdateProvider.update) {
int i = 0;
SocketTools.sendData(1, socket);
File file = new File("." + System.getProperty("file.separator").toString() + "update_package.jar");
OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream());
FileReader reader = new FileReader(file);
while ((i = reader.read()) != -1) {
writer.write(i);
}
writer.flush();
writer.close();
} else {
SocketTools.sendData(0, socket);
}
}
private Socket socket;
}
而我的客戶端代碼:
package de;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Main {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 16642);
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
//InputStreamReader reader = new InputStreamReader(s.getInputStream());
int i = 0;
FileWriter writer = new FileWriter(new File("C:\\update_package.jar"));
int state = reader.read();
if (state == 48) {
System.exit(0);
}
if (state == 49) {
while ((i = reader.read()) != -1) {
System.out.println(i);
writer.write(i);
}
System.out.println("ENDE");
writer.flush();
}
}
}
以「Writer」結尾的類是用於字符的。不適用於字節。 – SpiderPig