Ⅰ java 怎么写文件到ftp服务器
可以用文件流的方式直接写到服务器,也可以先在本地生成再调用ftp接口上传到服务器
Ⅱ 怎么向ftp中的txt文件写入数据
给 txt 加入 写权限和读权限。 通过客户端的FTP软件,右键 txt 文件,属性,加入 写,读。 请检查 文件路径是否正确!!!
Ⅲ ftp断点续传写不进去
intiBytes=soketData.Receive(buffer,bytesRead,0);
//套接字读取正确使用方法很多,但是没有只带两个int类型参数的方法,正确使用:
intiBytes=soketData.Receive(buffer);
//buffer----读取缓存。
//iBytes----实际接收的字节数。
output.Write(buffer,bytesRead,0);
//文件流写入方法的解释是这样的:
FileStream.Write(byte[]array,intoffset,intcount);
output.Write(buffer,0,bytesRead);
//array----代表要写入的byte[]数组。
//offset----代表写入位置的偏移量,你的程序这个位置应该是0。
//count----代表要写入的二进制数组的长度。
所以应该修改为:
while(true)
{
intiBytes=soketData.Receive(buffer);
output.Write(buffer,0,iBytes);
if(!(iBytes>0))
{
break;
}
}
建议你使用NetworkStream网络流来控制下载。
你的循环也不是很高效,如果网络出现延迟或中断,直接就退出循环了。应该有允许接收字节为0的次数限制。
给你写了段完整的,并不一定完全适合你,你可以根据需要修改。
//将套接字传入NetworkStream
NetworkStreamnetStream=newNetworkStream(socket);
//设置退出循环标志,首次等待数据。
boolStop=false,first=true;
intErrorTimes=0,MaxErrorTimes=10,BufferSize=1024*1024,ReadSize=0;
byte[]buffer=newbyte[BufferSize];
while(!Stop)
{
//netStream.DataAvailable检查网络流是否有数据可供读取
if(netStream.DataAvailable||first)
{
//循环读取可用数据写入文件
while(netStream.DataAvailable||first)
{
first=false;
ReadSize=netStream.Read(buffer,0,BufferSize);
output.Write(buffer,0,ReadSize);
}
//有数据到来,清零中断计数
ErrorTimes=0;
}
else
{
//允许网络中断计数累加
ErrorTimes++;
}
if(!(ErrorTimes<MaxErrorTimes))
{
//如果网络中断超过MaxErrorTimes,退出循环。
Stop=true;
}
}
Ⅳ c# FTP上传文件
C#ftp上传,参考如下:
///<summary>
///上传文件
///</summary>/
//<paramname="fileinfo">需要上传的文件</param>
///<paramname="targetDir">目标路径</param>
///<paramname="hostname">ftp地址</param>/
//<paramname="username">ftp用户名</param>/
//<paramname="password">ftp密码</param>
publicstaticvoidUploadFile(FileInfofileinfo,stringtargetDir,stringhostname,stringusername,stringpassword)
{//1.checktarget
stringtarget;
if(targetDir.Trim()=="")
{return;}
target=Guid.NewGuid().ToString();
//使用临时文件名
stringURI="FTP://"+hostname+"/"+targetDir+"/"+target;
///WebClientwebcl=newWebClient();
System.Net.FtpWebRequestftp=GetRequest(URI,username,password);
//设置FTP命令设置所要执行的FTP命令,
//ftp.Method=System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
ftp.Method=System.Net.WebRequestMethods.Ftp.UploadFile;
//指定文件传输的数据类型
ftp.UseBinary=true;
ftp.UsePassive=true;//告诉ftp文件大小
ftp.ContentLength=fileinfo.Length;
//缓冲大小设置为2KB
constintBufferSize=2048;
byte[]content=newbyte[BufferSize-1+1];
intdataRead;//打开一个文件流(System.IO.FileStream)去读上传的文件
using(FileStreamfs=fileinfo.OpenRead())
{
try{//把上传的文件写入流
using(Streamrs=ftp.GetRequestStream())
{do
{//每次读文件流的2KB
dataRead=fs.Read(content,0,BufferSize);rs.Write(content,0,dataRead);}
while(!(dataRead<BufferSize));rs.Close();}}
catch(Exceptionex){}finally{fs.Close();}}
ftp=null;//设置FTP命令
ftp=GetRequest(URI,username,password);
ftp.Method=System.Net.WebRequestMethods.Ftp.Rename;//改名
ftp.RenameTo=fileinfo.Name;try{ftp.GetResponse();}
catch(Exceptionex)
{
ftp=GetRequest(URI,username,password);ftp.Method=System.Net.WebRequestMethods.Ftp.DeleteFile;//删除
ftp.GetResponse();throwex;}finally
{
//fileinfo.Delete();}//可以记录一个日志"上传"+fileinfo.FullName+"上传到"+"FTP://"+hostname+"/"+targetDir+"/"+fileinfo.Name+"成功.");
ftp=null;
#region
/******FtpWebResponse*****///FtpWebResponseftpWebResponse=(FtpWebResponse)ftp.GetResponse();
#endregion
}
///<summary>
///下载文件
///</summary>
///<paramname="localDir">下载至本地路径</param>
///<paramname="FtpDir">ftp目标文件路径</param>
///<paramname="FtpFile">从ftp要下载的文件名</param>
///<paramname="hostname">ftp地址即IP</param>
///<paramname="username">ftp用户名</param>
///<paramname="password">ftp密码</param>
publicstaticvoidDownloadFile(stringlocalDir,stringFtpDir,stringFtpFile,stringhostname,stringusername,stringpassword)
{
stringURI="FTP://"+hostname+"/"+FtpDir+"/"+FtpFile;
stringtmpname=Guid.NewGuid().ToString();
stringlocalfile=localDir+@""+tmpname;
System.Net.FtpWebRequestftp=GetRequest(URI,username,password);
ftp.Method=System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary=true;
ftp.UsePassive=false;
using(FtpWebResponseresponse=(FtpWebResponse)ftp.GetResponse())
{
using(StreamresponseStream=response.GetResponseStream())
{
//looptoread&writetofile
using(FileStreamfs=newFileStream(localfile,FileMode.CreateNew))
{
try
{
byte[]buffer=newbyte[2048];
intread=0;
do
{
read=responseStream.Read(buffer,0,buffer.Length);
fs.Write(buffer,0,read);
}while(!(read==0));
responseStream.Close();
fs.Flush();
fs.Close();
}
catch(Exception)
{
//
fs.Close();
//deletetargetfileasit'sincomplete
File.Delete(localfile);
throw;
}
}
responseStream.Close();
}
response.Close();
}try
{
File.Delete(localDir+@""+FtpFile);
File.Move(localfile,localDir+@""+FtpFile);
ftp=null;
ftp=GetRequest(URI,username,password);
ftp.Method=System.Net.WebRequestMethods.Ftp.DeleteFile;
ftp.GetResponse();
}
catch(Exceptionex)
{
File.Delete(localfile);
throwex;
}
//记录日志"从"+URI.ToString()+"下载到"+localDir+@""+FtpFile+"成功.");
ftp=null;
}
///<summary>
///搜索远程文件
///</summary>
///<paramname="targetDir"></param>
///<paramname="hostname"></param>
///<paramname="username"></param>
///<paramname="password"></param>
///<paramname="SearchPattern"></param>
///<returns></returns>
publicstaticList<string>ListDirectory(stringtargetDir,stringhostname,stringusername,stringpassword,stringSearchPattern)
{
List<string>result=newList<string>();
try
{
stringURI="FTP://"+hostname+"/"+targetDir+"/"+SearchPattern;
System.Net.FtpWebRequestftp=GetRequest(URI,username,password);
ftp.Method=System.Net.WebRequestMethods.Ftp.ListDirectory;
ftp.UsePassive=true;
ftp.UseBinary=true;
stringstr=GetStringResponse(ftp);
str=str.Replace(" "," ").TrimEnd(' ');
str=str.Replace(" "," ");
if(str!=string.Empty)
result.AddRange(str.Split(' '));
returnresult;
}
catch{}
returnnull;
}
(FtpWebRequestftp)
{
//Gettheresult,streamingtoastring
stringresult="";
using(FtpWebResponseresponse=(FtpWebResponse)ftp.GetResponse())
{
longsize=response.ContentLength;
using(Streamdatastream=response.GetResponseStream())
{
using(StreamReadersr=newStreamReader(datastream,System.Text.Encoding.Default))
{
result=sr.ReadToEnd();
sr.Close();
}
datastream.Close();
}
response.Close();
}
returnresult;
}
///在ftp服务器上创建目录
///</summary>
///<paramname="dirName">创建的目录名称</param>
///<paramname="ftpHostIP">ftp地址</param>
///<paramname="username">用户名</param>
///<paramname="password">密码</param>
publicvoidMakeDir(stringdirName,stringftpHostIP,stringusername,stringpassword)
{
try
{
stringuri="ftp://"+ftpHostIP+"/"+dirName;
System.Net.FtpWebRequestftp=GetRequest(uri,username,password);
ftp.Method=WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponseresponse=(FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch(Exceptionex)
{
MessageBox.Show(ex.Message);
}
}
///<summary>
///删除目录
///</summary>
///<paramname="dirName">创建的目录名称</param>
///<paramname="ftpHostIP">ftp地址</param>
///<paramname="username">用户名</param>
///<paramname="password">密码</param>
publicvoiddelDir(stringdirName,stringftpHostIP,stringusername,stringpassword)
{
try
{
stringuri="ftp://"+ftpHostIP+"/"+dirName;
System.Net.FtpWebRequestftp=GetRequest(uri,username,password);
ftp.Method=WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponseresponse=(FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch(Exceptionex)
{
MessageBox.Show(ex.Message);
}
}
///<summary>
///文件重命名
///</summary>
///<paramname="currentFilename">当前目录名称</param>
///<paramname="newFilename">重命名目录名称</param>
///<paramname="ftpServerIP">ftp地址</param>
///<paramname="username">用户名</param>
///<paramname="password">密码</param>
publicvoidRename(stringcurrentFilename,stringnewFilename,stringftpServerIP,stringusername,stringpassword)
{
try
{
FileInfofileInf=newFileInfo(currentFilename);
stringuri="ftp://"+ftpServerIP+"/"+fileInf.Name;
System.Net.FtpWebRequestftp=GetRequest(uri,username,password);
ftp.Method=WebRequestMethods.Ftp.Rename;
ftp.RenameTo=newFilename;
FtpWebResponseresponse=(FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch(Exceptionex){MessageBox.Show(ex.Message);}}
(stringURI,stringusername,stringpassword)
{
//根据服务器信息FtpWebRequest创建类的对象
FtpWebRequestresult=(FtpWebRequest)FtpWebRequest.Create(URI);
//提供身份验证信息
result.Credentials=newSystem.Net.NetworkCredential(username,password);
//设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
result.KeepAlive=false;
returnresult;
}
Ⅳ FTP 改文件写入权限 FTP文件夹的写入权限
通过shell登陆服务器修改。可能ftp服务器配置成不允许FTP客户端修改权限.
Ⅵ php ftp_get 如何写入本地文件
ftp_get
仅是下载,如果本地有内容你不想覆盖的话那就按照时间戳变更下载后的文件名,如果要对文件进行操作
PHP写入文件需要:打开文件fopen()、写入数据fwrite()和关闭文件
fclose()
$fp=fopen("../cnbruce.txt",'w');
r
只读——读模式,打开文件,从文件头开始读
r+
可读可写方式打开文件,从文件头开始读写
w
只写——写方式打开文件,同时把该文件内容清空,把文件指针指向文件开始处。如果该文件已经存在,将删除文件已有内容;如果该文件不存在,则建立该文件
w+
可读可写方式打开文件,同时把该文件内容清空,把文件指针指向文件开始处。如果该文件不存在,则建立该文件
a
追加
以只写方式打开文件,把文件指针指向文件末尾处。如果该文件不存在,则建立该文件
a+
追加
以可读可写方式打开文件,把文件指针指向文件末尾处。如果该文件不存在,则建立该文件
b
二进制
用于于其他模式进行连接。建议使用该选项,以获得更大程度的可移植性
注意,如果fopen()函数调用失败,函数将返回false。否则返回指针数据。所以一般在打开了文件后\读写文件前需要检测下文件是否存在。
Ⅶ 采用ftpclient.storeFile(String, Inputstream)将流写到服务器,没报错但服务器上没有文件,这是怎么回事
//创建一个FtpClient对象
FTPClient ftpClient = new FTPClient();
//上传文件 - 读取本地文件 file:需要上传的文件地址
FileInputStream inputStream = new FileInputStream(file);
//将流写到服务器
ftpclient.storeFile(String, inputStream)
其中String为保存后的文件名,inputStream就是上面获取的文件流
向上面说的服务器上没有文件,
1、可能是你String前面加了地址,但是你的ftp服务器中没有这个文件夹导致的,
2、在以有的文件夹下上传保存,在String前面加/文件夹名,
例:ftpClient.storeFile("/***"+String, inputStream);
(多层文件夹时)有的时候你需要给ftp文件夹设置权限(右击文件夹选择属性--安全--编辑--永许完全控制),可以试一试。最好只用当前层文件夹,否则每层都要设置
3、
ftpClient.makeDirectory("/文件名");//创建文件夹
ftpClient.changeWorkingDirectory("/文件名");改变保存路径
这种的最好只用一层文件夹路径
本人彩笔一枚,大佬请喷。喷完了请把解决思路说一下!!!
Ⅷ 大哥 ,采用ftpclient.storeFile(String, Inputstream)将流写到服务器,没报错但服务器上没有文件,这个问
FTP协议有两种工作方式:PORT方式和PASV方式,中文意思为主动式和被动式。 PORT(主动)方式的连接过程是:客户端向服务器的FTP端口(默认是21)发送连接请 求,服务器接受连接,建立一条命令链路。当需要传送数据时,客户端在命令链路上用PORT 命令告诉服务器:“我打开了XXXX端口,你过来连接我”。于是服务器从20端口向客户端的 XXXX端口发送连接请求,建立一条数据链路来传送数据。 PASV(被动)方式的连接过程是:客户端向服务器的FTP端口(默认是21)发送连接请 求,服务器接受连接,建立一条命令链路。当需要传送数据时,服务器在命令链路上用PASV 命令告诉客户端:“我打开了XXXX端口,你过来连接我”。于是客户端向服务器的XXXX端口 发送连接请求,建立一条数据链路来传送数据。
我当时因为连的是别人的服务器,那边换了服务器就出现这问题,后来我通过FTPClient有一个ftpclient.enterLocalPassiveMode()方法,设置后就没有这问题了,不知道你是不是跟我一样
Ⅸ C# 将FTP文件转移到另一个FTP服务器上如何实现
C# ftp上传ftp
/// <summary>
/// 上传文件
/// </summary> /
// <param name="fileinfo">需要上传的文件</param>
/// <param name="targetDir">目标路径</param>
/// <param name="hostname">ftp地址</param> /
// <param name="username">ftp用户名</param> /
// <param name="password">ftp密码</param>
public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password)
{ //1. check target
string target;
if (targetDir.Trim() == "")
{ return; }
target = Guid.NewGuid().ToString();
//使用临时文件名
string URI = "FTP://" + hostname + "/" + targetDir + "/" + target;
///WebClient webcl = new WebClient();
System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
//设置FTP命令 设置所要执行的FTP命令,
//ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
//指定文件传输的数据类型
ftp.UseBinary = true;
ftp.UsePassive = true; //告诉ftp文件大小
ftp.ContentLength = fileinfo.Length;
//缓冲大小设置为2KB
const int BufferSize = 2048;
byte[] content = new byte[BufferSize - 1 + 1];
int dataRead; //打开一个文件流 (System.IO.FileStream) 去读上传的文件
using (FileStream fs = fileinfo.OpenRead())
{
try { //把上传的文件写入流
using (Stream rs = ftp.GetRequestStream())
{ do
{ //每次读文件流的2KB
dataRead = fs.Read(content, 0, BufferSize); rs.Write(content, 0, dataRead); }
while (!(dataRead < BufferSize)); rs.Close(); } }
catch (Exception ex) { } finally { fs.Close(); } }
ftp = null; //设置FTP命令
ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
ftp.RenameTo = fileinfo.Name; try { ftp.GetResponse(); }
catch (Exception ex)
{
ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
ftp.GetResponse(); throw ex; } finally
{
//fileinfo.Delete(); } // 可以记录一个日志 "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
ftp = null;
#region
/***** *FtpWebResponse * ****/ //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse();
#endregion
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="localDir">下载至本地路径</param>
/// <param name="FtpDir">ftp目标文件路径</param>
/// <param name="FtpFile">从ftp要下载的文件名</param>
/// <param name="hostname">ftp地址即IP</param>
/// <param name="username">ftp用户名</param>
/// <param name="password">ftp密码</param>
public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
{
string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
string tmpname = Guid.NewGuid().ToString();
string localfile = localDir + @"\" + tmpname;
System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
ftp.UsePassive = false;
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
//loop to read & write to file
using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
{
try
{
byte[] buffer = new byte[2048];
int read = 0;
do
{
read = responseStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);
} while (!(read == 0));
responseStream.Close();
fs.Flush();
fs.Close();
}
catch (Exception)
{
//catch error and delete file only partially downloaded
fs.Close();
//delete target file as it's incomplete
File.Delete(localfile);
throw;
}
}
responseStream.Close();
}
response.Close();
}
try
{
File.Delete(localDir + @"\" + FtpFile);
File.Move(localfile, localDir + @"\" + FtpFile);
ftp = null;
ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
ftp.GetResponse();
}
catch (Exception ex)
{
File.Delete(localfile);
throw ex;
}
// 记录日志 "从" + URI.ToString() + "下载到" + localDir + @"\" + FtpFile + "成功." );
ftp = null;
}
/// <summary>
/// 搜索远程文件
/// </summary>
/// <param name="targetDir"></param>
/// <param name="hostname"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="SearchPattern"></param>
/// <returns></returns>
public static List<string> ListDirectory(string targetDir, string hostname, string username, string password, string SearchPattern)
{
List<string> result = new List<string>();
try
{
string URI = "FTP://" + hostname + "/" + targetDir + "/" + SearchPattern;
System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
ftp.UsePassive = true;
ftp.UseBinary = true;
string str = GetStringResponse(ftp);
str = str.Replace("\r\n", "\r").TrimEnd('\r');
str = str.Replace("\n", "\r");
if (str != string.Empty)
result.AddRange(str.Split('\r'));
return result;
}
catch { }
return null;
}
private static string GetStringResponse(FtpWebRequest ftp)
{
//Get the result, streaming to a string
string result = "";
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
long size = response.ContentLength;
using (Stream datastream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(datastream, System.Text.Encoding.Default))
{
result = sr.ReadToEnd();
sr.Close();
}
datastream.Close();
}
response.Close();
}
return result;
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
/// <summary>
/// 向Ftp服务器上传文件并创建和本地相同的目录结构
/// 遍历目录和子目录的文件
/// </summary>
/// <param name="file"></param>
private void GetFileSystemInfos(FileSystemInfo file)
{
string getDirecName=file.Name;
if (!ftpIsExistsFile(getDirecName, "192.168.0.172", "Anonymous", "") && file.Name.Equals(FileName))
{
MakeDir(getDirecName, "192.168.0.172", "Anonymous", "");
}
if (!file.Exists) return;
DirectoryInfo dire = file as DirectoryInfo;
if (dire == null) return;
FileSystemInfo[] files = dire.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
FileInfo fi = files[i] as FileInfo;
if (fi != null)
{
DirectoryInfo DirecObj=fi.Directory;
string DireObjName = DirecObj.Name;
if (FileName.Equals(DireObjName))
{
UploadFile(fi, DireObjName, "192.168.0.172", "Anonymous", "");
}
else
{
Match m = Regex.Match(files[i].FullName, FileName + "+.*" + DireObjName);
//UploadFile(fi, FileName+"/"+DireObjName, "192.168.0.172", "Anonymous", "");
UploadFile(fi, m.ToString(), "192.168.0.172", "Anonymous", "");
}
}
else
{
string[] ArrayStr = files[i].FullName.Split('\\');
string finame=files[i].Name;
Match m=Regex.Match(files[i].FullName,FileName+"+.*"+finame);
//MakeDir(ArrayStr[ArrayStr.Length - 2].ToString() + "/" + finame, "192.168.0.172", "Anonymous", "");
MakeDir(m.ToString(), "192.168.0.172", "Anonymous", "");
GetFileSystemInfos(files[i]);
}
}
}
/// <summary>
/// 判断ftp服务器上该目录是否存在
/// </summary>
/// <param name="dirName"></param>
/// <param name="ftpHostIP"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
private bool ftpIsExistsFile(string dirName, string ftpHostIP, string username, string password)
{
bool flag = true;
try
{
string uri = "ftp://" + ftpHostIP + "/" + dirName;
System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
ftp.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception )
{
flag = false;
}
return flag;
}
Ⅹ 为什么我用FTP传文件是老说有权限文件写入
在ftp服务器配置中设置你的帐号有写入、删除、建立子目录等相应权限即可实现写入。