我对Java和C#非常陌生。我有一个Java应用程序,正在使用TCP套接字将文件名和文件发送到C#客户端。我收到了数据,但是在写入时它已损坏。我不知道如何首先读取文件名,然后再将其余数据写入文件。
我已经编写了代码,如果我只是从Java应用程序发送文件,则可以在C#应用程序上成功接收到该文件并成功写入。这有效100%。现在我要发送名称和文件。
Java代码发送数据:
try {
System.out.println("Connecting...");
File file = new File(Environment.getExternalStorageDirectory(), backup_folder);
File[] Files = file.listFiles();
OutputStream os = m_socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(Files.length);
for (int count = 0; count < Files.length; count++) {
dos.writeUTF(Files[count].getName());
}
for (int count = 0; count < Files.length; count++) {
int filesize = (int) Files[count].length();
dos.writeInt(filesize);
}
for (int count = 0; count < Files.length; count++) {
int filesize = (int) Files[count].length();
byte[] buffer = new byte[filesize];
FileInputStream fis = new FileInputStream(Files[count].toString());
BufferedInputStream bis = new BufferedInputStream(fis);
//Sending file name and file size to the server
bis.read(buffer, 0, buffer.length); //This line is important
dos.write(buffer, 0, buffer.length);
dos.flush();
//close socket connection
//socket.close();
}
m_socket.close();
} catch (Exception e) {
System.out.println("Error::" + e);
//System.out.println(e.getMessage());
//e.printStackTrace();
//Log.i("******* :( ", "UnknownHostException");
}
}
C#代码(这是我遇到的问题)
private void WaitConnection()
{
toolStripStatusLabel2.Visible = true;
toolStripStatusLabel1.Visible = false;
while (true){
m_listener.Start();
m_client = m_listener.AcceptTcpClient();
if (m_client.Connected == true)
{
this.Invoke((MethodInvoker)delegate
{
this.toolStripStatusLabel4.Visible = false;
this.toolStripStatusLabel5.Visible = false;
this.toolStripStatusLabel3.Visible = true;
});
}
using (var stream = m_client.GetStream())
using (var output = File.Create("C:\\Stocktake\\EDADatabase.db"))
{
byte[] buffer;
buffer = new byte[1024];
int bytesRead = -1;
progressBar1.BeginInvoke(new MethodInvoker(delegate { progressBar1.Maximum = 50; })); //Set Progessbar maximum
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
var xml = Encoding.UTF8.GetString(buffer,0,bytesRead);
string rec = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
output.Write(buffer, 0, bytesRead);
progressBar1.Invoke(new updatebar(this.UpdateProgress));
}
if (bytesRead == 0)
{
Completed = true;
this.Invoke((MethodInvoker)delegate
{
this.m_client.GetStream().Close();
this.m_client.Dispose();
this.m_listener.Stop();
this.toolStripStatusLabel3.Visible = false;
this.toolStripStatusLabel5.Visible = true;
});
progressBar1.Invoke(new updatebar(this.UpdateProgress));
//break;
}
}
}
}
我要做的就是读取文件名,然后使用文件名读取数据并将其保存到我的电脑中。