本文目錄一覽:
用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怎麼把文件傳輸到伺服器
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方法
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如何實現文件上傳
public static int transFile(InputStream in, OutputStream out, int fileSize) {
int receiveLen = 0;
final int bufSize = 1000;
try {
byte[] buf = new byte[bufSize];
int len = 0;
while(fileSize – receiveLen bufSize)
{
len = in.read(buf);
out.write(buf, 0, len);
out.flush();
receiveLen += len;
System.out.println(len);
}
while(receiveLen fileSize)
{
len = in.read(buf, 0, fileSize – receiveLen);
System.out.println(len);
out.write(buf, 0, len);
receiveLen += len;
out.flush();
}
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
return receiveLen;
}
這個方法從InputStream中讀取內容,寫到OutputStream中。
那麼發送文件方,InputStream就是FileInputStream,OutputStream就是Socket.getOutputStream.
接受文件方,InputStream就是Socket.getInputStream,OutputStream就是FileOutputStream。
就OK了。 至於存到資料庫里嘛,Oracle里用Blob。搜索一下,也是一樣的。從Blob能獲取一個輸出流。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/155342.html