我正在使用Java在客户端和服务器之间发送文本。这是通过从客户端向服务器发送字节流来完成的。然后将从字节流转换的字符串保存到带有时间戳的文件夹中,从而将其写入文件。不幸的是,空格以及意外字符(例如“ ^ @”)都将与预期的文本一起写入文件。
这可能是什么问题?我认为这可能是字符串转换错误的缓冲区,但我可能错了。
我已附加了来自终端的运行时输出以及所有我认为发生问题的有用代码。对于这个问题的解释,而不只是一个答案,将是最有益的,因为我想了解为什么会发生这种错误。
主要方法:
public static void main(String[] args) {
startServer();
String date = createDateString();
String miniDate = createMiniDateString();
System.out.println("hello, we are still waiting to start...");
try {
Socket connection;
OutputStream tx;
InputStream rx;
connection = server_.accept(); // waits for connection
tx = connection.getOutputStream();
rx = connection.getInputStream();
server_.close(); // no need to wait now
System.out.println("We are here now");
System.out.println("New connection ... " +
connection.getInetAddress().getHostName() + ":" +
connection.getPort());
byte[] buffer = new byte[bufferSize_];
int b = 0;
while (b < 1) {
Thread.sleep(sleepTime_);
buffer = new byte[bufferSize_];
b = rx.read(buffer);
}
if (b > 0) {
//I believe the problem might be due to buffer to string conversion
String s = new String(buffer); //this is the message, we might have to store it in an array instead?
System.out.println("Received " + b + " bytes --> " + s);
System.out.println("***** this is the string: *****"+s);
System.out.println("Sending " + b + " bytes");
tx.write(buffer, 0, b); // send data back to client
createDirectory(s, date, miniDate);
connection.close(); // finished
}
}
catch (SocketTimeoutException e) {
// no incoming data - just ignore
}
catch (InterruptedException e) {
System.err.println("Interrupted Exception: " + e.getMessage());
}
catch (IOException e) {
System.err.println("IO Exception: " + e.getMessage());
}
}
createDirectory方法:
public static void createDirectory(String s, String date, String miniDate){
String dirName = new String(date);//time1
String fileName = new String(miniDate); //time2
String text = new String(s); //message
File dir = new File(dirName); //copy these raw at first and then clean it up as a new method
if (dir.exists()) {
System.out.println("++ File already exists: " + dirName);
//System.exit(0);
}
if (dir.mkdir()) {
System.out.println("++ Created directory: " + dirName);
}
else {
System.out.println("++ Failed to create directory: " + dirName);
//System.exit(0);
}
fileName = dirName + File.separator + fileName;
File file = new File(fileName);
if (file.exists()) {
System.out.println("++ File already exists: " + fileName);
//System.exit(0);
}
try {
FileWriter fw = new FileWriter(file);
fw.write(text);
fw.flush();
fw.close();
}
catch (IOException e) {
System.out.println("IOException - write(): " + e.getMessage());
}
System.out.println("++ Wrote \"" + text + "\" to file: " + fileName);
}
答案 0 :(得分:0)
您正在尝试将整个缓冲区(全部bufferSize_
个字节)转换为String,但是缓冲区的仅前b
个字节包含从客户端接收的数据。使用
String s = new String(buffer, 0, b);
仅转换字节数组的前b
个字节(请参阅此answer)