filesend.java
来自「JAVA 文件传输 发送文件 接受文件」· Java 代码 · 共 78 行
JAVA
78 行
package fileclient;
import java.net.*;
import java.io.*;
public class FileSend {
public static void main(String[] args) {
String fName = "d:/1.exe";
Socket soc = null;
InputStream is = null;
OutputStream os = null;
FileInputStream fis = null;
BufferedReader br = null;
BufferedWriter bw = null;
String msg = "";
File f = new File(fName);
try {
soc = new Socket("127.0.0.1", 9999);
System.out.println("connect server ok!");
is = soc.getInputStream();
os = soc.getOutputStream();
bw = new BufferedWriter(
new OutputStreamWriter(os));
br = new BufferedReader(
new InputStreamReader(is));
fis = new FileInputStream(fName);
bw.write("SendFile");
bw.newLine();
bw.flush();
msg = br.readLine();
if (msg.equals("FileName")) {
bw.write(f.getName());
bw.newLine();
bw.flush();
msg = br.readLine();
if (msg.equals("FileSize")) {
bw.write(""+f.length());
bw.newLine();
bw.flush();
msg = br.readLine();
if (msg.equals("Ready")) {
byte[] bs = new byte[fis.available()];
int bt = -1;
fis.read(bs,0,bs.length);
//while ((bt = fis.read(bs, 0, bs.length)) > 0) {
os.write(bs, 0, bs.length);
//}
fis.close();
msg = br.readLine();
if (msg.equals("Finished")) {
System.out.println("file send success!");
}
}
}
}
} catch (Exception ex) {
System.out.println("ex in client:" +
ex.getMessage());
} finally {
try {
bw.close();
} catch (Exception ex) {}
try {
br.close();
} catch (Exception ex) {}
try {
is.close();
} catch (Exception ex) {}
try {
os.close();
} catch (Exception ex) {}
try {
soc.close();
} catch (Exception ex) {}
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?