導航:首頁 > 編程語言 > java讀取上傳文件

java讀取上傳文件

發布時間:2023-01-15 07:17:17

java web開發,上傳圖片並讀取

java web開發中,使用文件操作類來上傳圖片並讀取,如下代碼:

*@desc:圖片處理工具
*@author:bingye
*@createTime:2015-3-17下午04:25:32
*@version:v1.0
*/
publicclassImageUtil{

/**
*將圖片寫到客戶端
*@author:bingye
*@createTime:2015-3-17下午04:36:04
*@history:
*@paramimage
*@paramresponsevoid
*/
publicstaticvoidwriteImage(byte[]image,HttpServletResponseresponse){
if(image==null){
return;
}
byte[]buffer=newbyte[1024];
InputStreamis=null;
OutputStreamos=null;
try{
is=newByteArrayInputStream(image);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(is!=null){is.close();}
if(os!=null){os.close();}
}catch(IOExceptione){
e.printStackTrace();
}
}
}

/**
*獲取指定路勁圖片
*@author:bingye
*@createTime:2015-3-21上午10:50:44
*@paramfilePath
*@paramresponsevoid
*/
publicstaticvoidwriteImage(StringfilePath,HttpServletResponseresponse){
FileimageFile=newFile(filePath);
if(imageFile!=null&&imageFile.exists()){
byte[]buffer=newbyte[1024];
InputStreamis=null;
OutputStreamos=null;
try{
is=newFileInputStream(imageFile);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(is!=null){is.close();}
if(os!=null){os.close();}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}

/**
*圖片上傳到文件夾
*@author:bingye
*@createTime:2015-3-20下午08:07:25
*@paramfile
*@paramsavePath
*@returnboolean
*/
(CommonsMultipartFilefile,StringsavePath){
if(file!=null&&!file.isEmpty()){
//獲取文件名稱
StringfileName=file.getOriginalFilename();
//獲取後綴名
StringsuffixName=fileName.substring(fileName.indexOf(".")+1);
//新名稱
StringnewFileName=System.currentTimeMillis()+"."+suffixName;
//新文件路勁
StringfilePath=savePath+newFileName;
//獲取存儲文件路徑
FilefileDir=newFile(savePath);
if(!fileDir.exists()){
//如果文件夾沒有:新建
fileDir.mkdirs();
}
FileOutputStreamfos=null;
try{
fos=newFileOutputStream(filePath);
fos.write(file.getBytes());
fos.flush();
returnResultUtil.success("UPLOAD_SUCCESS",URLEncoder.encode(newFileName,"utf-8"));
}catch(Exceptione){
e.printStackTrace();
returnResultUtil.fail("UPLOAD_ERROR");
}finally{
try{
if(fos!=null){
fos.close();
}
}catch(IOExceptione){
e.printStackTrace();
returnResultUtil.fail("UPLOAD_ERROR");
}
}
}
returnResultUtil.fail("UPLOAD_ERROR");
}}

Ⅱ java怎麼獲取上傳文件的路徑

java文件中獲得路徑
Thread.currentThread().getContextClassLoader().getResource("") //獲得資源文件(.class文件)所在路徑
ClassLoader.getSystemResource("")
Class_Name.class.getClassLoader().getResource("")
Class_Name.class .getResource("/")
Class_Name.class .getResource("") // 獲得當前類所在路徑
System.getProperty("user.dir") // 獲得項目根目錄的絕對路徑
System.getProperty("java.class.path") //得到類路徑和包路徑
列印輸出依次如下:
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/com/xml/imp/
F:\work_litao\uri_test
F:\work_litao\uri_test\WebContent\WEB-INF\classes;F:\work_litao\uri_test\WebContent\WEB-INF\lib\dom4j.jar
2、 JSP中獲得當前應用的相對路徑和絕對路徑
根目錄所對應的絕對路徑:request.getRequestURI()
文件的絕對路徑 :application.getRealPath(request.getRequestURI());
當前web應用的絕對路徑 :application.getRealPath("/");
取得請求文件的上層目錄:new File(application.getRealPath(request.getRequestURI())).getParent()

Ⅲ java中怎樣上傳文件

Java代碼實現文件上傳

FormFilefile=manform.getFile();
StringnewfileName=null;
Stringnewpathname=null;
StringfileAddre="/numUp";
try{
InputStreamstream=file.getInputStream();//把文件讀入
StringfilePath=request.getRealPath(fileAddre);//取系統當前路徑
Filefile1=newFile(filePath);//添加了自動創建目錄的功能
((File)file1).mkdir();
newfileName=System.currentTimeMillis()
+file.getFileName().substring(
file.getFileName().lastIndexOf('.'));
ByteArrayOutputStreambaos=newByteArrayOutputStream();
OutputStreambos=newFileOutputStream(filePath+"/"
+newfileName);
newpathname=filePath+"/"+newfileName;
System.out.println(newpathname);
//建立一個上傳文件的輸出流
System.out.println(filePath+"/"+file.getFileName());
intbytesRead=0;
byte[]buffer=newbyte[8192];
while((bytesRead=stream.read(buffer,0,8192))!=-1){
bos.write(buffer,0,bytesRead);//將文件寫入伺服器
}
bos.close();
stream.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
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能獲取一個輸出流。

Ⅳ 如何用java讀取客戶端上傳的rar文件

直接通過工具類進行解壓或者壓縮文件即可。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
*
* @author gdb
*/
public class ZipUtilAll {
public static final int DEFAULT_BUFSIZE = 1024 * 16;

/**
* 解壓Zip文件
*
* @param srcZipFile
* @param destDir
* @throws IOException
*/
public static void unZip(File srcZipFile, String destDir) throws IOException
{
ZipFile zipFile = new ZipFile(srcZipFile);
unZip(zipFile, destDir);
}

/**
* 解壓Zip文件
*
* @param srcZipFile
* @param destDir
* @throws IOException
*/
public static void unZip(String srcZipFile, String destDir) throws IOException
{
ZipFile zipFile = new ZipFile(srcZipFile);
unZip(zipFile, destDir);
}

/**
* 解壓Zip文件
*
* @param zipFile
* @param destDir
* @throws IOException
*/
public static void unZip(ZipFile zipFile, String destDir) throws IOException
{
Enumeration<? extends ZipEntry> entryEnum = zipFile.entries();
ZipEntry entry = null;
while (entryEnum.hasMoreElements()) {
entry = entryEnum.nextElement();
File destFile = new File(destDir + entry.getName());
if (entry.isDirectory()) {
destFile.mkdirs();
}
else {
destFile.getParentFile().mkdirs();
InputStream eis = zipFile.getInputStream(entry);
System.out.println(eis.read());
write(eis, destFile);
}
}
}

/**
* 將輸入流中的數據寫到指定文件
*
* @param inputStream
* @param destFile
*/
public static void write(InputStream inputStream, File destFile) throws IOException
{
BufferedInputStream bufIs = null;
BufferedOutputStream bufOs = null;
try {
bufIs = new BufferedInputStream(inputStream);
bufOs = new BufferedOutputStream(new FileOutputStream(destFile));
byte[] buf = new byte[DEFAULT_BUFSIZE];
int len = 0;
while ((len = bufIs.read(buf, 0, buf.length)) > 0) {
bufOs.write(buf, 0, len);
}
} catch (IOException ex) {
throw ex;
} finally {
close(bufOs, bufIs);
}
}

/**
* 安全關閉多個流
*
* @param streams
*/
public static void close(Closeable... streams)
{
try {
for (Closeable s : streams) {
if (s != null)
s.close();
}
} catch (IOException ioe) {
ioe.printStackTrace(System.err);
}
}

/**
* @param args
* @throws java.lang.Exception
*/
public static void main(String[] args) throws Exception
{
// unZip(new File(ZipDemo.class.getResource("D:/123/HKRT-B2B.zip").toURI()), "D:/123/");
unZip("D:/123/123.zip", "D:/123/");
// new File();
}
}

Ⅵ 怎麼在java中上傳文檔和讀取文檔

1.文件上傳
package com.whw.action;
import java.io.File;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport implements ServletContextAware {
private static final long serialVersionUID = 1L;
private File upload;// 實際上傳文件
private String uploadContentType; // 文件的內容類型
private String uploadFileName; // 文件 名稱
private String fileCaption;// 上傳文件時的備注
private ServletContext context;
public String execute() throws Exception {
try {
String targetDirectory = context.getRealPath("/upload");
String targetFileName = fileCaption+uploadFileName;
File target = new File(targetDirectory, targetFileName);
FileUtils.File(upload, target);
setUploadFileName(target.getPath());//保存文件的存放路徑
} catch (Exception e) {
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
public String getFileCaption() {
return fileCaption;
}
public void setFileCaption(String fileCaption) {
this.fileCaption = fileCaption;
}
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public void setServletContext(ServletContext context) {
this.context = context;
}
}

2.讀取文件夾下的文件
package sample;
import java.io.*;
public class CopyFileStream{ // one file to another file
public static void main(String args[]) {
FileInputStream fromFile=null;
FileOutputStream toFile=null;
try{
//生成兩個已有byte文件的 流對象。
fromFile=new FileInputStream(args[0]); // get file name from console
toFile=new FileOutputStream(args[1]); // get file name from console
} catch (FileNotFoundException e){
System.err.println("File could not be found");
return; //缺文件名輸入,拋異常,返回。
} catch (IOException e){
System.err.println("File could not be copied ");
return;
} catch ( e){
System.err.println("Usage: CopyByteFile from-file to-file");
return;
}
try {
fromFile.close(); // close InputStream
toFile.close(); // close OutputStream
}catch (IOException e){
System.err.println("Error closing File.");
}
}
}
File類下的exists();方法是判斷文件是否存在返回值是boolean

希望是你需要的。

Ⅶ java上傳txt文件後讀取內容

告訴你很麻煩

FormFile upfile = fileupForm.getFilecontext();// 獲取客戶端選中的文件實體
FileReader fr = new FileReader(upfile);
BufferedReader br = new BufferedReader(fr);
String line="";
int lineNum=0;
while((line=br.readLine())!=null){
System.out.println(line);
lineNum++;
if(lineNum==N) break; //當讀取的行數為自定義的行數N時break.退出
}
br.close();
fr.close();

Ⅷ java怎麼讀取文件夾中的內容並上傳

FileInputStream fis = new FileInputStream("d:/a.txt");//從a.txt中讀出
FileOutputStream fos = new FileOutputStream("d:/b.txt");//寫到b.txt中去
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(fos));
String temp;
while((temp = reader.readLine())!= null){//一次讀一行
write.write(temp);
}
reader.close();
write.close();

Ⅸ java項目中文件的上傳與讀取

互聯網項目一般會有單獨的伺服器存放靜態資源,圖片就是一種靜態資源,在這里就是區別於項目部署的另一台伺服器。這時候你項目裡面都是使用相對路徑,像你上面所說的常量/opt/upload/這種做法是正確的,上傳圖片的時候,常見的有使用日期分目錄存儲的,如/opt/upload/2014/11/03/***.jpg,對於圖片的路徑,資料庫里一般來說保存到2014/11/03/***.jpg就可以了。這是存圖片。
取圖片,一般來說資源都必須發布服務才能讓外網訪問。例如,你可以在你項目中寫個servlet用來讀取圖片,如下面的服務地址http://ip:port/projectname/image/2014/11/03/***.jpg,其中2014前面的路徑是固定的,後面的是你資料庫里存儲的圖片地址,這時你頁面代碼裡面只需固定前綴http://ip:port/projectname/image + 圖片相對地址則可將圖片讀出來。
上面這種方法用的其實比較少,一般來說靜態伺服器都會部署一個web容器,然後使用單獨的域名,打個比方,你在靜態伺服器上有個tomcat,目錄/opt/tomcat/webapp/staticprojectname,staticprojectname是工程名,然後在上傳的所有圖片在staticprojectname下面,例如/opt/tomcat/webapp/staticprojectname/2014/11/03/***.jpg,然後在你原工程裡面直接使用http://靜態服務ip:port/staticprojectname/2014/11/03/***.jpg就可以訪問到圖片了,同樣的在你代碼裡面2014前面的地址是固定的,配置成常量,後面的則是資料庫里存的圖片相對地址。
說了這么多,有點亂,希望你能明白

Ⅹ Java 如何讀取頁面上傳文件

socket網路編程的方法可以用getInputStream()方法讀入 這種方法比較老 現在來講 對於web程序的上傳都會應用一些現有的開源組件 比較好的就是FileUpload組件 隸屬commons-fileupload-x.x.x.jar 現在好像最新的是隨struts2.1.6發布的commons-fileupload-1.2.1.jar
FileUpload這個組件可以運用在struts或者常規Servlet中實現文件上傳

閱讀全文

與java讀取上傳文件相關的資料

熱點內容
拍賣程序員 瀏覽:101
電腦的圖片放在哪個文件夾 瀏覽:274
unsignedintjava 瀏覽:216
編譯器下載地址 瀏覽:42
什麼是面對對象編程 瀏覽:708
b站伺服器什麼時候恢復 瀏覽:721
6p相當於安卓機什麼水準 瀏覽:498
能否給隱藏相冊加密 瀏覽:596
糖心app改什麼名 瀏覽:823
戰地1控伺服器如何部署 瀏覽:394
xp還原系統輸入命令 瀏覽:323
mysql命令行版本 瀏覽:303
如何進入itunes找文件夾 瀏覽:832
CAD中重復命令使用 瀏覽:478
心智pdf 瀏覽:475
網站電台直播間源碼 瀏覽:852
文件夾14c和18c的區別 瀏覽:36
android隱式調用 瀏覽:668
plc的編程指令邊沿繼電器 瀏覽:723
voc文件夾 瀏覽:866