导航:首页 > 编程语言 > 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读取上传文件相关的资料

热点内容
扣扣加密技巧 浏览:720
苹果如何创建服务器错误 浏览:495
软考初级程序员大题分值 浏览:473
js压缩视频文件 浏览:578
linux如何通过命令创建文件 浏览:989
应用加密app还能访问应用嘛 浏览:433
安卓怎么用支付宝交违章罚款 浏览:665
php面向对象的程序设计 浏览:504
数据挖掘算法书籍推荐 浏览:894
投诉联通用什么app 浏览:150
web服务器变更ip地址 浏览:954
java正则表达式验证邮箱 浏览:360
成熟商务男装下载什么软件app 浏览:609
加密2h代表长度是多少厘米 浏览:23
拍卖程序员 浏览:102
电脑的图片放在哪个文件夹 浏览:276
unsignedintjava 浏览:217
编译器下载地址 浏览:43
什么是面对对象编程 浏览:709
b站服务器什么时候恢复 浏览:722