fileService类中
//添加文件
public boolean addFile(File f){
try {
String sql="insert into socket_file(fname,fcontent) value(?,?)";
conn=DBUtil.getconnection();
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, f.getFname());
ps.setBytes(2, f.getFcontent());
ps.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
socketClient类中
//文件上传
public void showAddfile(){
System.out.println("请输入要上传的文件的觉得路径(如:e:/imooc/dog.jpg):");
File file=new File();
String path=input.next();
CommandTansfer transfer=new CommandTansfer();
FileInputStream fis=null;
BufferedInputStream bis=null;
java.io.File fileInfo=new java.io.File(path);
if(fileInfo.exists()&&fileInfo.isFile()){
file.setFname(fileInfo.getName());
transfer.setCmd("addFile");
try {
fis=new FileInputStream(fileInfo);
byte[] fcontent=new byte[fis.available()];
bis=new BufferedInputStream(fis);
bis.read(fcontent);
file.setFcontent(fcontent);
transfer.setData(file);
//与服务器进行通信
socket=new Socket("127.0.0.1", 8858);
sendData(transfer);
//接收服务器数据
CommandTansfer result=getData();
if(result.isFlag()){
System.out.println("********上传文件成功********");
}else{
System.out.println("********上传文件失败********");
}
fis.close();
bis.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
//向服务器发送数据
private void sendData(CommandTansfer transfer){
OutputStream out;
try {
out = socket.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(out);
oos.writeObject(transfer);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
//接收服务器的数据
private CommandTansfer getData(){
CommandTansfer result=null;
try {
ObjectInputStream ois=new ObjectInputStream(
socket.getInputStream());
result=(CommandTansfer)ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return result;
}