我有一个小应用程序,用于创建和填充SQLITE数据库(路径=“ /home/henri/TFA-Nexus/data.db”)。
将来,我想使用套接字将数据传输到同一网络中的另一台设备。 我的想法是通过套接字通过字符串将.db文件从客户端传输到服务器。
在我的本地系统上对此进行仿真,我得到另一个.db文件(路径=“ /home/henri/TFA-Nexus/data2.db”),其字节与“ / home / henri / TFA-Nexus / data”完全相同。D b”。
MyClient.java
public static void main(String[] args) {
try{
System.out.println("[Client] Connecting to server...");
Socket s=new Socket("localhost",6666);
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(s.getInputStream()));
out.writeUTF(readStringFromFile());
out.flush();
System.out.println("[Client] Sent data...");
out.close();
s.close();
System.out.println("[Client] Closed connection...");
}catch(Exception e){
e.printStackTrace();
}
}
private static String readStringFromFile() throws IOException {
File file = new File("/home/henri/TFA-Nexus/data.db");
InputStream in = new FileInputStream(file);
byte[] b = new byte[(int) file.length()];
int len = b.length;
int total = 0;
while (total < len) {
int result = in.read(b, total, len - total);
if (result == -1) {
break;
}
total += result;
}
return new String( b , StandardCharsets.UTF_8 );
}
MyServer.java
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
System.out.println("[SERVER] Waiting for client...");
Socket s=ss.accept();
DataInputStream dis=new DataInputStream(s.getInputStream());
System.out.println("[SERVER] Reading 'data'...");
String str = (String) dis.readUTF();
System.out.println("[SERVER] Writing string to file...");
writeStringToFile(str);
System.out.println("[SERVER] Closing connection...");
ss.close();
}catch(Exception e){
e.printStackTrace();
}
}
private static void writeStringToFile(String s) throws IOException {
Files.write(Paths.get("/home/henri/TFA-Nexus/data2.db"), s.getBytes());
}
几乎所有的东西都在工作。我得到一个名为“ data2.db”的新文件,其大小相同:
但是打开文件时出现以下错误:
此错误的原因是什么?我的想法错了吗?