c#获取指定目录下最新的文件传输到JAVA服务端
c#客户端
using Spire.Pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp6
{
//自定义一个类
public class FileTimeInfo
{
public string FileName; //文件名
public DateTime FileCreateTime; //创建时间
}
class Program
{
static void Main(string[] args)
{
//使用 GetLatestFileTimeInfo
//获取d:\test文件中,扩展名为.pdf的最新文件
FileTimeInfo fi = GetLatestFileTimeInfo(@"d:\test", ".pdf");
if (fi != null)
{
Console.WriteLine("文件名:{0} 创建时间:{1}", fi.FileName, fi.FileCreateTime);
Console.WriteLine(Path.GetFileName(fi.FileName));
}
else
{
Console.WriteLine("文件夹中没有指定扩展名的文件!");
}
StartSend(fi.FileName, Path.GetFileName(fi.FileName));
}
//获取最近创建的文件名和创建时间
//如果没有指定类型的文件,返回null
static FileTimeInfo GetLatestFileTimeInfo(string dir, string ext)
{
List<FileTimeInfo> list = new List<FileTimeInfo>();
DirectoryInfo d = new DirectoryInfo(dir);
foreach (FileInfo fi in d.GetFiles())
{
if (fi.Extension.ToUpper() == ext.ToUpper())
{
list.Add(new FileTimeInfo()
{
FileName = fi.FullName,
FileCreateTime = fi.CreationTime
});
}
}
var qry = from x in list
orderby x.FileCreateTime
select x;
return qry.LastOrDefault();
}
static int StartSend(string path, string fileName)
{
if (!File.Exists(path))
{
return -1;
}
NetworkStream stream = null;
BinaryWriter sw = null;
FileStream fsMyfile = null;
BinaryReader brMyfile = null;
try
{
TcpClient client = new TcpClient("192.168.1.103", 8888);
stream = client.GetStream();
sw = new BinaryWriter(stream);
///取得文件名字节数组
byte[] fileNameBytes = Encoding.Default.GetBytes(fileName);
byte[] fileNameBytesArray = new byte[1024];
Array.Copy(fileNameBytes, fileNameBytesArray, fileNameBytes.Length);
///写入流
sw.Write(fileNameBytesArray, 0, fileNameBytesArray.Length);
sw.Flush();
///获取文件内容字节数组
///byte[] fileBytes = returnbyte(filePath);
fsMyfile = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
brMyfile = new BinaryReader(fsMyfile);
///写入流
byte[] buffer = new byte[1024];
int count = 0;
while ((count = brMyfile.Read(buffer, 0, 1024)) > 0)
{
sw.Write(buffer, 0, count);
sw.Flush();
buffer = new byte[1024];
}
}
catch (SocketException se)
{
Console.WriteLine(se.StackTrace);
return -2;
}
catch (IOException ioe)
{
Console.WriteLine(ioe.StackTrace);
return -3;
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
return -4;
}
finally
{
if (sw != null)
{
sw.Close();
}
if (brMyfile != null)
{
brMyfile.Close();
}
if (fsMyfile != null)
{
fsMyfile.Close();
}
if (stream != null)
{
stream.Close();
}
}
return 0;
}
}
}
JAVA服务端
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
public class TCPServer{
private static Logger logger = Logger.getLogger(TCPServer.class);
private static String path;
private static int port;
static{
System.out.print("读取配置文件...");
//资源绑定
ResourceBundle rb = ResourceBundle.getBundle("config", Locale.getDefault());
path = rb.getString("path");
String portStr = rb.getString("port");
if(path == null || path.trim().equals("")){
path = "E:/";
}else if(!path.endsWith("/")){
path = path + "/";
}
if(portStr != null || !portStr.trim().equals("")){
try{
port = Integer.parseInt(portStr);
}catch(Exception ex){
System.out.println("端口获取失败,已变更为默认端口8888");
port = 8888;
}
}else{
System.out.println("未配置端口,已变更为默认端口8888");
port = 8888;
}
System.out.println("读取完成:" + "接收端口" + port + ",接收路径" + path);
}
public static void main(String[] args){
new TCPServer().receiveFile();
}
public void receiveFile(){
ServerSocket ss = null;
Socket s = null;
BufferedInputStream in = null;
FileOutputStream out = null;
try{
ss = new ServerSocket(port);
System.out.println("服务已正常启动!");
}catch(Exception ex){
ex.printStackTrace();
System.out.println("服务启动失败!");
logger.error("启动服务失败!" + ex);
}
//永不停歇地运行
while(true){
byte[] buffer = new byte[1024];
String fileName = null;
try{
s = ss.accept();
in = new BufferedInputStream(s.getInputStream());
//取得文件名
in.read(buffer, 0, buffer.length);
fileName = new String(buffer).trim();
//若为测试信息
if(fileName.equals("test message")){
System.out.println("接收到测试消息!");
logger.info("接收到测试消息!");
continue;
}
//定义文件流
out = new FileOutputStream(
new File(path + new SimpleDateFormat("yyyymmddhhmmss").format(new Date()) + fileName));
out.flush();
buffer = new byte[1024];
//写文件内容
int count = 0;
while((count = in.read(buffer, 0, buffer.length)) > 0){
out.write(buffer, 0, count);
out.flush();
buffer = new byte[1024];
}
System.out.println("接收到文件" + fileName);
logger.info("接收到文件" + fileName);
}catch(Exception ex){
System.out.println("传输异常");
logger.error("传输异常", ex);
ex.printStackTrace();
}finally{
try{
if(out != null){
out.close();
}
if(in != null){
in.close();
}
if(s != null){
s.close();
}
}catch(Exception ex){
ex.printStackTrace();
logger.error("接收文件" + fileName + "失败" + ex);
}
}
}
}
}
配置文件
path=F://
port=8888