62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.*;
/**
* 本程序通过socket编程实现从客户端发送文件到服务器端
* @author ×××
*/
class FileTimer extends TimerTask{
public void run(){
byte[] buffer = new byte[1024];
int length = 0;
try {
Socket socket = new Socket("localhost", 5100);
File f = new File("d:\\text\\");
File[] tempFile=f.listFiles();
if(tempFile!=null){
for(int i=0;i<tempFile.length;i++){
FileInputStream fis = new FileInputStream(tempFile[i]);
DataInputStream dataIn = new DataInputStream(fis);
DataOutputStream dataOut = new DataOutputStream(socket
.getOutputStream());
while ((length = dataIn.read(buffer)) != -1) {
dataOut.write(buffer, 0, length);
}
dataOut.flush();
dataOut.close();
fis.close();
tempFile[i].delete();
System.out.println("文件传送完毕!!!");
socket.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class FileClient {
public static void main(String[] args) {
Timer a=new Timer();
a.schedule(new FileTimer(), 0, 60000);
}
}
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.text.*;
/**
* 本程序通过socket编程实现从客户端发送文件到服务器端
* @author ×××
*/
/**
* 构造一个现在时间为基点的字符串作为文件输入文件的文件名
*/
class TimeStr{
//Date CurrentTime=new Date();
public static String getTimeStr() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
String dateString = formatter.format(currentTime);
String[] str=dateString.split(" ");
return "D:\\rec\\"+str[0]+str[1]+".txt";
}
}
/**
* 多线程类实现服务器一直都在监听
*/
class MultiServer extends Thread{
private Socket socket;
private DataInputStream dataIn;
private FileOutputStream out;
int length=0;
byte[] buffer=new byte[1024];
public MultiServer(Socket s)throws IOException{
socket=s;
dataIn= new DataInputStream(socket.getInputStream());
File f = new File(TimeStr.getTimeStr());
if (!f.exists())
f.createNewFile();
out = new FileOutputStream(f);
start();
}
public void run(){
try{
while((length=dataIn.read(buffer))!=-1){
out.write(buffer, 0, length);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
out.flush();
out.close();
System.out.println("服务器端文件接收完毕!!!");
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
//
public class FileServer {
static final int PORT=5100;
public static void main(String[] a)throws IOException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("服务器启动!");
try{
while(true){
Socket socket=s.accept();
try{
new MultiServer(socket);
}catch(IOException e){
socket.close();
e.printStackTrace();
}
}
}catch(IOException e){
e.printStackTrace();
}finally{
s.close();
}
}
}