本文目錄一覽:
- 1、用Java實現在兩台電腦之間的文件傳輸
- 2、java怎麼把文件傳輸到file
- 3、java中怎樣上傳文件
- 4、java 服務器與客戶端的文件傳輸
- 5、java socket如何實現一次傳送多個文件
- 6、java怎麼把文件傳輸到服務器
用Java實現在兩台電腦之間的文件傳輸
使用Socket可以做到,不過直接編程一般都是在局域網內,如果要在不同局域網間通信,需要使用一台有公網IP的服務器,可以電腦A和電腦B同時連接服務器,然後A向服務器傳遞文件,服務器再將文件轉發電腦B。也可以使用打洞的方式使A、B互聯,此時服務器的作用是輔助打洞。A、B向服務器發送信息後socket不要關閉(假設使用10989端口),同時使用Serversocket綁定監聽相同的端口(監聽10989端口)。在java中有參數可以做到,具體方法請自行百度。服務器獲取到A、B的外網地址和端口,將A的外網地址信息發送給B、將B的外網地址信息發送給A。然後使用A沒有關閉的Socket向B發送一組信息(此時連接會失敗,但是B的路由表上已經記錄了A的信息),發送後A向服務器發送消息,服務器告訴B A已經發送消息。然後B使用未關閉的socket向A發送消息,就和A上監聽的ServerSocket取得連接了。之後就可以互相傳遞數據。
java怎麼把文件傳輸到file
common-fileupload是jakarta項目組開發的一個功能很強大的上傳文件組件
下面先介紹上傳文件到服務器(多文件上傳):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = “text/html; charset=GB2312”;
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
try {
DiskFileUpload fu = new DiskFileUpload();
// 設置允許用戶上傳文件大小,單位:位元組,這裡設為2m
fu.setSizeMax(2*1024*1024);
// 設置最多只允許在內存中存儲的數據,單位:位元組
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬盤的目錄
fu.setRepositoryPath(“c://windows//temp”);
//開始讀取上傳信息
List fileItems = fu.parseRequest(request);
// 依次處理每個上傳的文件
Iterator iter = fileItems.iterator();
//正則匹配,過濾路徑取文件名
String regExp=”.+////(.+)$”;
//過濾掉的文件類型
String[] errorType={“.exe”,”.com”,”.cgi”,”.asp”};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是文件域的所有表單信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals(“”)) size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;tempERRORTYPE.LENGTH;TEMP++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+”: wrong type”);
}
}
try{
//保存上傳的文件到指定的目錄
//在下文中上傳文件至數據庫時,將對這裡改寫
item.write(new File(“d://” + m.group(1)));
out.print(name+” “+size+””);
}
catch(Exception e){
out.println(e);
}
}
else
{
throw new IOException(“fail to upload”);
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}
}
}
現在介紹上傳文件到服務器,下面只寫出相關代碼:
以sql2000為例,表結構如下:
字段名:name filecode
類型: varchar image
數據庫插入代碼為:PreparedStatement pstmt=conn.prepareStatement(“insert into test values(?,?)”);
代碼如下:
。。。。。。
try{
這段代碼如果不去掉,將一同寫入到服務器中
//item.write(new File(“d://” + m.group(1)));
int byteread=0;
//讀取輸入流,也就是上傳的文件內容
InputStream inStream=item.getInputStream();
pstmt.setString(1,m.group(1));
pstmt.setBinaryStream(2,inStream,(int)size);
pstmt.executeUpdate();
inStream.close();
out.println(name+” “+size+” “);
}
。。。。。。
這樣就實現了上傳文件至數據庫
java中怎樣上傳文件
Java代碼實現文件上傳
FormFile file=manform.getFile();
String newfileName = null;
String newpathname=null;
String fileAddre=”/numUp”;
try {
InputStream stream = file.getInputStream();// 把文件讀入
String filePath = request.getRealPath(fileAddre);//取系統當前路徑
File file1 = new File(filePath);//添加了自動創建目錄的功能
((File) file1).mkdir();
newfileName = System.currentTimeMillis()
+ file.getFileName().substring(
file.getFileName().lastIndexOf(‘.’));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath + “/”
+ newfileName);
newpathname=filePath+”/”+newfileName;
System.out.println(newpathname);
// 建立一個上傳文件的輸出流
System.out.println(filePath+”/”+file.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);// 將文件寫入服務器
}
bos.close();
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
java 服務器與客戶端的文件傳輸
可以直接通過流的形式上傳或者下載。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import hkrt.b2b.view.util.Log;
import java.util.Vector;
import zn.ccfccb.util.CCFCCBUtil;
/**
*/
public class CCFCCBSftp {
/**
* 連接sftp服務器
*
* @return
*/
public static ChannelSftp connect() {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(CCFCCBUtil.CCFCCBHOSTNAME, CCFCCBUtil.CCFCCBHOSTNAME, 22);
Session sshSession = jsch.getSession(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBHOSTNAME, 22);
System.out.println(“Session created.”);
sshSession.setPassword(CCFCCBUtil.CCFCCBLOGINPASSWORD);
Properties sshConfig = new Properties();
sshConfig.put(“StrictHostKeyChecking”, “no”);
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println(“Session connected.”);
System.out.println(“Opening Channel.”);
Channel channel = sshSession.openChannel(“sftp”);
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println(“Connected to ” + CCFCCBUtil.CCFCCBHOSTNAME + “.”);
} catch (Exception e) {
}
return sftp;
}
/**
* 連接sftp服務器
*
* @param host 主機
* @param port 端口
* @param username 用戶名
* @param password 密碼
* @return
*/
public static ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(CCFCCBUtil.CCFCCBHOSTNAME, CCFCCBUtil.CCFCCBHOSTNAME, 22);
Session sshSession = jsch.getSession(CCFCCBUtil.CCFCCBLOGINNAME, host, port);
System.out.println(“Session created.”);
sshSession.setPassword(CCFCCBUtil.CCFCCBLOGINPASSWORD);
Properties sshConfig = new Properties();
sshConfig.put(“StrictHostKeyChecking”, “no”);
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println(“Session connected.”);
System.out.println(“Opening Channel.”);
Channel channel = sshSession.openChannel(“sftp”);
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println(“Connected to ” + host + “.”);
} catch (Exception e) {
}
return sftp;
}
/**
* 上傳文件
*
* @param directory 上傳的目錄
* @param uploadFile 要上傳的文件
* @param sftp
*/
public void upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
s;
File file = new File(uploadFile);
s(new FileInputStream(file), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下載文件
*
* @param directory 下載目錄
* @param downloadFile 下載的文件
* @param saveFile 存在本地的路徑
* @param sftp
* @return
*/
public static String download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
try {
s;
File file = new File(saveFile);
FileOutputStream fos = new FileOutputStream(file);
s(downloadFile, fos);
s;
fos.close();
} catch (Exception e) {
Log.info(“下載文件過程出錯:” + e.getMessage());
return “false”;
}
return “true”;
}
/**
* 刪除文件
*
* @param directory 要刪除文件所在目錄
* @param deleteFile 要刪除的文件
* @param sftp
*/
public void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
s;
s;
} catch (Exception e) {
}
}
/**
* 列出目錄下的文件
*
* @param directory 要列出的目錄
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory, ChannelSftp sftp) throws SftpException {
return s;
}
public static void main(String[] args) {
CCFCCBSftp sf = new CCFCCBSftp();
String host = CCFCCBUtil.CCFCCBHOSTNAME;
int port = 22;
String username = CCFCCBUtil.CCFCCBLOGINNAME;
String password = CCFCCBUtil.CCFCCBLOGINPASSWORD;
String directory = “/ccfccb/904999900099/download/”;
//String uploadFile = “D:\\tmp\\upload.txt”;
String downloadFile = “CCF_904999900099_20150317_0001.zip”;
String saveFile = CCFCCBUtil.CCFCCBUploadFilePath + “//” + “CCF_904999900099_20150317_0001.zip”;
//String deleteFile = “delete.txt”;
ChannelSftp sftp = CCFCCBS(host, port, username, password);
//sf.upload(directory, uploadFile, sftp);
CCFCCBS(directory, downloadFile, saveFile, sftp);
//sf.delete(directory, deleteFile, sftp);
try {
s;
// s(“ss”);
System.out.println(“finished”);
} catch (Exception e) {
}
}
}
java socket如何實現一次傳送多個文件
很簡單,就是把多個文件「變成」一個文件傳送就可以了,每個文件都是一個流,把這些流輸入到一個流中合併流傳輸即可,這個是基本思路。實現差不多以下兩個方法
1、直接流拼接,循環要傳輸的文件列表,多個InputStream,然後輸出到一個OutputStream,這個out就是發送數據的端口,為了接收端能夠識別每個文件從而分割流,需要每個流中結尾添加分隔符。其實這就是HTTP文件上傳的做法。
2、就比較簡單了,職業使用ZIP工具包吧需要傳輸的多文件壓縮成一個文件傳輸,接收端直接解壓縮就完事。
需要注意的是,發送多文件上傳你需要提取計算好總傳輸量位元組大小放在傳輸報文頭部告訴接收端你要發送的數據有多大,不然接收端可能無法完整接收數據。
java怎麼把文件傳輸到服務器
String realpath = ServletActionContext.getServletContext().getRealPath(“/upload”) ;//獲取服務器路徑
String[] targetFileName = uploadFileName;
for (int i = 0; i upload.length; i++) {
File target = new File(realpath, targetFileName[i]);
FileUtils.copyFile(upload[i], target);
//這是一個文件複製類copyFile()裏面就是IO操作,如果你不用這個類也可以自己寫一個IO複製文件的類
}
其中private File[] upload;// 實際上傳文件
private String[] uploadContentType; // 文件的內容類型
private String[] uploadFileName; // 上傳文件名
這三個參數必須這樣命名,因為文件上傳控件默認是封裝了這3個參數的,且在action裏面他們應有get,set方法
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/309158.html