JAVA如何得到文件路径

JAVA如何得到文件路径,第1张

要得到什么文件路径``

在你要用路径的时候 比如 <img src="XXXXXXXX"></ing>

中间的XXXXXX你就这么写`先把原来的文件路径用STRING 形式存在数据库`

现在取出来`赋给变量 abc

在这里再写成

String abc = "你的文件路径"

<img src="<%=ABC%>"></ing>

可以通过“ 类名classgetResource("")getPath()”方法实现。

举例:”String path = XMLSclassgetResource("")getPath()“

解释:以上语句就是获取到XMLS编译后的绝对路径(无法获取到java文件路径的,因为java运行的都是class文件)。

public static void main(String[] args) {

// TODO Auto-generated method stub

// 创建File对象

File file = new File("d:\\");

// 使用递归方法做

dg(file);

}

private static void dg(File fl) {

// TODO Auto-generated method stub

// 创建file数组用来存储数据

File[] filArr = fllistFiles();

// 判断FiLe数组不能为空

if (filArr != null) {

// 使用for遍历

for (File f : filArr) {

// 如果是文件夹 就递归

if (fisDirectory()) {

// 递归

dg(f);

} else if (fisFile()) {

Systemoutprintln(fgetAbsolutePath());

}

}

}

}

上传文件时,我想获取客户端上传文件的原始路径。第一考虑,当然是使用js,例如网上可以找到的:

function getPath(obj) { if (obj) { if (windownavigatoruserAgentindexOf("MSIE") >= 1) { objselect(); return documentselectioncreateRange()text; } else if (windownavigatoruserAgentindexOf("Firefox") >= 1) { if (objfiles) { return objfilesitem(0)getAsDataURL(); } return objvalue; } return objvalue; } } 但这样的代码在Ie下还是可行的,但在火狐下不兼容。所以又想通过servlet的第三方工具去做,例如FileUpload,本以为FileItem下的getName()方法能够得到全路径名,但结果仍然只得到文件名,很是杯具!求解决方法!?

引用<input type="file" name="file" />至于你说的,不明白你的意思关键问题是我要获得这个路径,并且传递到后台!用js会有兼容性问题,如果用FileUpload上传,是否可以获得呢?我是没有得到的!!! 问题补充:zhanjia 写道上传文件一般用input标签,type为file,浏览选择文件后就是文件在本地的绝对路径了

引用<input type="file" name="file" />至于你说的,不明白你的意思关键的问题是我要获得这个本地路径,并且传到后台!用js可以得到,但存在兼容性问题!?如果用FileUpload呢?我暂时还没有得到!!! 问题补充:zhanjia 写道网上的一些解决方案:

一般都是上传以后在数据库中保存上传后的文件路径,本地路径一般没意义

除非像上面所说的文件上传预览,还有那么点用处

我用来做数据接口的,我仅仅是把路径传给另一个系统,然后那个系统就可以从这个路径取文件了。如果先上传一次,再给对方,这样不但影响上传速度,而且会产生大量的垃圾文件。

package comweixinutil;

import javaioFile;

import javaioFileOutputStream;

import javaioIOException;

import javaioInputStream;

import javaioOutputStream;

import javaioPrintWriter;

import javaioRandomAccessFile;

import orgapachecommonsnetPrintCommandListener;

import orgapachecommonsnetftpFTP;

import orgapachecommonsnetftpFTPClient;

import orgapachecommonsnetftpFTPFile;

import orgapachecommonsnetftpFTPReply;

import comweixinconstantDownloadStatus;

import comweixinconstantUploadStatus;

/

支持断点续传的FTP实用类

@version 01 实现基本断点上传下载

@version 02 实现上传下载进度汇报

@version 03 实现中文目录创建及中文文件创建,添加对于中文的支持

/

public class ContinueFTP {

public FTPClient ftpClient = new FTPClient();

public ContinueFTP(){

//设置将过程中使用到的命令输出到控制台

thisftpClientaddProtocolCommandListener(new PrintCommandListener(new PrintWriter(Systemout)));

}

/

连接到FTP服务器

@param hostname 主机名

@param port 端口

@param username 用户名

@param password 密码

@return 是否连接成功

@throws IOException

/

public boolean connect(String hostname,int port,String username,String password) throws IOException{

ftpClientconnect(hostname, port);

ftpClientsetControlEncoding("GBK");

if(FTPReplyisPositiveCompletion(ftpClientgetReplyCode())){

if(ftpClientlogin(username, password)){

return true;

}

}

disconnect();

return false;

}

/

从FTP服务器上下载文件,支持断点续传,上传百分比汇报

@param remote 远程文件路径

@param local 本地文件路径

@return 上传的状态

@throws IOException

/

public DownloadStatus download(String remote,String local) throws IOException{

//设置被动模式

ftpCliententerLocalPassiveMode();

//设置以二进制方式传输

ftpClientsetFileType(FTPBINARY_FILE_TYPE);

DownloadStatus result;

//检查远程文件是否存在

FTPFile[] files = ftpClientlistFiles(new String(remotegetBytes("GBK"),"iso-8859-1"));

if(fileslength != 1){

Systemoutprintln("远程文件不存在");

return DownloadStatusRemote_File_Noexist;

}

long lRemoteSize = files[0]getSize();

File f = new File(local);

//本地存在文件,进行断点下载

if(fexists()){

long localSize = flength();

//判断本地文件大小是否大于远程文件大小

if(localSize >= lRemoteSize){

Systemoutprintln("本地文件大于远程文件,下载中止");

return DownloadStatusLocal_Bigger_Remote;

}

//进行断点续传,并记录状态

FileOutputStream out = new FileOutputStream(f,true);

ftpClientsetRestartOffset(localSize);

InputStream in = ftpClientretrieveFileStream(new String(remotegetBytes("GBK"),"iso-8859-1"));

byte[] bytes = new byte[1024];

long step = lRemoteSize /100;

long process=localSize /step;

int c;

while((c = inread(bytes))!= -1){

outwrite(bytes,0,c);

localSize+=c;

long nowProcess = localSize /step;

if(nowProcess > process){

process = nowProcess;

if(process % 10 == 0)

Systemoutprintln("下载进度:"+process);

//TODO 更新文件下载进度,值存放在process变量中

}

}

inclose();

outclose();

boolean isDo = ftpClientcompletePendingCommand();

if(isDo){

result = DownloadStatusDownload_From_Break_Success;

}else {

result = DownloadStatusDownload_From_Break_Failed;

}

}else {

OutputStream out = new FileOutputStream(f);

InputStream in= ftpClientretrieveFileStream(new String(remotegetBytes("GBK"),"iso-8859-1"));

byte[] bytes = new byte[1024];

long step = lRemoteSize /100;

long process=0;

long localSize = 0L;

int c;

while((c = inread(bytes))!= -1){

outwrite(bytes, 0, c);

localSize+=c;

long nowProcess = localSize /step;

if(nowProcess > process){

process = nowProcess;

if(process % 10 == 0)

Systemoutprintln("下载进度:"+process);

//TODO 更新文件下载进度,值存放在process变量中

}

}

inclose();

outclose();

boolean upNewStatus = ftpClientcompletePendingCommand();

if(upNewStatus){

result = DownloadStatusDownload_New_Success;

}else {

result = DownloadStatusDownload_New_Failed;

}

}

return result;

}

/

上传文件到FTP服务器,支持断点续传

@param local 本地文件名称,绝对路径

@param remote 远程文件路径,使用/home/directory1/subdirectory/fileext 按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构

@return 上传结果

@throws IOException

/

public UploadStatus upload(String local,String remote) throws IOException{

//设置PassiveMode传输

ftpCliententerLocalPassiveMode();

//设置以二进制流的方式传输

ftpClientsetFileType(FTPBINARY_FILE_TYPE);

ftpClientsetControlEncoding("GBK");

UploadStatus result;

//对远程目录的处理

String remoteFileName = remote;

if(remotecontains("/")){

remoteFileName = remotesubstring(remotelastIndexOf("/")+1);

//创建服务器远程目录结构,创建失败直接返回

if(CreateDirecroty(remote, ftpClient)==UploadStatusCreate_Directory_Fail){

return UploadStatusCreate_Directory_Fail;

}

}

//检查远程是否存在文件

FTPFile[] files = ftpClientlistFiles(new String(remoteFileNamegetBytes("GBK"),"iso-8859-1"));

if(fileslength == 1){

long remoteSize = files[0]getSize();

File f = new File(local);

long localSize = flength();

if(remoteSize==localSize){

return UploadStatusFile_Exits;

}else if(remoteSize > localSize){

return UploadStatusRemote_Bigger_Local;

}

//尝试移动文件内读取指针,实现断点续传

result = uploadFile(remoteFileName, f, ftpClient, remoteSize);

//如果断点续传没有成功,则删除服务器上文件,重新上传

if(result == UploadStatusUpload_From_Break_Failed){

if(!ftpClientdeleteFile(remoteFileName)){

return UploadStatusDelete_Remote_Faild;

}

result = uploadFile(remoteFileName, f, ftpClient, 0);

}

}else {

result = uploadFile(remoteFileName, new File(local), ftpClient, 0);

}

return result;

}

/

断开与远程服务器的连接

@throws IOException

/

public void disconnect() throws IOException{

if(ftpClientisConnected()){

ftpClientdisconnect();

}

}

/

递归创建远程服务器目录

@param remote 远程服务器文件绝对路径

@param ftpClient FTPClient对象

@return 目录创建是否成功

@throws IOException

/

public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{

UploadStatus status = UploadStatusCreate_Directory_Success;

String directory = remotesubstring(0,remotelastIndexOf("/")+1);

if(!directoryequalsIgnoreCase("/")&&!ftpClientchangeWorkingDirectory(new String(directorygetBytes("GBK"),"iso-8859-1"))){

//如果远程目录不存在,则递归创建远程服务器目录

int start=0;

int end = 0;

if(directorystartsWith("/")){

start = 1;

}else{

start = 0;

}

end = directoryindexOf("/",start);

while(true){

String subDirectory = new String(remotesubstring(start,end)getBytes("GBK"),"iso-8859-1");

if(!ftpClientchangeWorkingDirectory(subDirectory)){

if(ftpClientmakeDirectory(subDirectory)){

ftpClientchangeWorkingDirectory(subDirectory);

}else {

Systemoutprintln("创建目录失败");

return UploadStatusCreate_Directory_Fail;

}

}

start = end + 1;

end = directoryindexOf("/",start);

//检查所有目录是否创建完毕

if(end <= start){

break;

}

}

}

return status;

}

/

上传文件到服务器,新上传和断点续传

@param remoteFile 远程文件名,在上传之前已经将服务器工作目录做了改变

@param localFile 本地文件File句柄,绝对路径

@param processStep 需要显示的处理进度步进值

@param ftpClient FTPClient引用

@return

@throws IOException

/

public UploadStatus uploadFile(String remoteFile,File localFile,FTPClient ftpClient,long remoteSize) throws IOException{

UploadStatus status;

//显示进度的上传

long step = localFilelength() / 100;

long process = 0;

long localreadbytes = 0L;

RandomAccessFile raf = new RandomAccessFile(localFile,"r");

OutputStream out = ftpClientappendFileStream(new String(remoteFilegetBytes("GBK"),"iso-8859-1"));

//断点续传

if(remoteSize>0){

ftpClientsetRestartOffset(remoteSize);

process = remoteSize /step;

rafseek(remoteSize);

localreadbytes = remoteSize;

}

byte[] bytes = new byte[1024];

int c;

while((c = rafread(bytes))!= -1){

outwrite(bytes,0,c);

localreadbytes+=c;

if(localreadbytes / step != process){

process = localreadbytes / step;

Systemoutprintln("上传进度:" + process);

//TODO 汇报上传状态

}

}

outflush();

rafclose();

outclose();

boolean result =ftpClientcompletePendingCommand();

if(remoteSize > 0){

status = resultUploadStatusUpload_From_Break_Success:UploadStatusUpload_From_Break_Failed;

}else {

status = resultUploadStatusUpload_New_File_Success:UploadStatusUpload_New_File_Failed;

}

return status;

}

public static void main(String[] args) {

ContinueFTP myFtp = new ContinueFTP();

try {

Systemerrprintln(myFtpconnect("10106236", 21, "5", "jieyan"));

// myFtpftpClientmakeDirectory(new String("歌曲"getBytes("GBK"),"iso-8859-1"));

// myFtpftpClientchangeWorkingDirectory(new String("歌曲"getBytes("GBK"),"iso-8859-1"));

// myFtpftpClientmakeDirectory(new String("爱你等于爱自己"getBytes("GBK"),"iso-8859-1"));

// Systemoutprintln(myFtpupload("E:\\ywflv", "/ywflv",5));

// Systemoutprintln(myFtpupload("E:\\爱你等于爱自己mp4","/爱你等于爱自己mp4"));

//Systemoutprintln(myFtpdownload("/爱你等于爱自己mp4", "E:\\爱你等于爱自己mp4"));

myFtpdisconnect();

} catch (IOException e) {

Systemoutprintln("连接FTP出错:"+egetMessage());

}

}

}

读取配置文件 , xxxproperties放在webroot/WEB-INF/classes/目录下

首先将配置文件转换成InputStream,有两种方式,原理一样,都是通过类加载器得到资源:

(1)InputStream inputStream = ThreadcurrentThread()getContextClassLoader()getResourceAsStream("xxproperties");

(2) InputStream inputStream =

thisgetClass() getClassLoader()getResourceAsStream( "xxproperties" );

调用对象的getClass()方法是获得对象当前的类类型,这部分数据存在方法区中,

而后在类类型上调用 getClassLoader()方法是得到当前类型的类加载器,我们知道在Java中所有的类都是通过加载器加载到虚拟机中的,而且类加载器之间存在父 子关系,就是子知道父,父不知道子,这样不同的子加载的类型之间是无法访问的(虽然它们都被放在方法区中),所以在这里通过当前类的加载器来加载资源也就 是保证是和类类型同一个加载器加载的。

最后调用了类加载器的getResourceAsStream()方法来加载资源。

(3) 然后加载配置文件,读取属性值

Properties prop = new Properties();

propload(input);

String value = propgetProperty("PropertyName");

inputclose();

在jsp和class文件中调用的相对路径不同。在jsp里,根目录是WebRoot 在class文件中,根目录是WebRoot/WEB-INF/classes 当然你也可以用SystemgetProperty("userdir")获取工程的绝对路径。

另:在Jsp,Servlet,Java中详细获得路径的方法!

1jsp中取得路径:

以工程名为TEST为例:

(1)得到包含工程名的当前页面全路径:requestgetRequestURI()

结果:/TEST/testjsp

(2)得到工程名:requestgetContextPath()

结果:/TEST

(3)得到当前页面所在目录下全名称:requestgetServletPath()

结果:如果页面在jsp目录下 /TEST/jsp/testjsp

(4)得到页面所在服务器的全路径:applicationgetRealPath("页面jsp")

结果:D:\resin\webapps\TEST\testjsp

(5)得到页面所在服务器的绝对路径:absPath=new javaioFile(applicationgetRealPath(requestgetRequestURI()))getParent();

结果:D:\resin\webapps\TEST

2在类中取得路径:

(1)类的绝对路径:ClassclassgetClass()getResource("/")getPath()

结果:/D:/TEST/WebRoot/WEB-INF/classes/pack/

(2)得到工程的路径:SystemgetProperty("userdir")

结果:D:\TEST

3在Servlet中取得路径:

(1)得到工程目录:requestgetSession()getServletContext()getRealPath("") 参数可具体到包名。

结果:E:\Tomcat\webapps\TEST

(2)得到IE地址栏地址:requestgetRequestURL()

结果:>

以上就是关于JAVA如何得到文件路径全部的内容,包括:JAVA如何得到文件路径、java怎么根据文件名获取文件绝对路径、java怎么获取ftp文件的路径等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/10056972.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-04
下一篇 2023-05-04

发表评论

登录后才能评论

评论列表(0条)

保存