关闭→
当前位置:知科普>综合知识>java读取文件路径怎么写

java读取文件路径怎么写

知科普 人气:3.19W
1. java web中读取文件,相对路径怎么写

相对路径的话,可以先获取到当前文件的编译路径,之后在找到想找文件的路径的思路来实现。

java读取文件路径怎么写

举例:

XMLS.class.getClass().getResourceAsStream("/test/test.txt");

解释:XMLS.class.getClass()是获取当前的类编译路径,之后通过getResourceAsStream的形式即可找到要读取的文件的路径。

备注:这个方法中后面的路径也可以通过截取的形式来进行路径获取,实现原理都是找到当前类路径,之后通过相对位置找到另外文件路径。

2. java获取某个文件夹的路径怎么写

File类有两个常用方法可以得到文件路径一个是:getCanonicalPath(),另一个是:getAbsolutePath(),可以通过File类的实例调用这两个方法例如file.getAbsolutePath()其中file是File的实例对象。下面是一个具体例子:

public class PathTest

{

public static void main(String[] args)

{

File file = new File(".srcbaidu");

System.out.println(file.getAbsolutePath());

try

{

System.out.println(file.getCanonicalPath());

} catch (IOException e)

{

e.printStackTrace();

}

}

}

getAbsolutePath()和getCanonicalPath()的不同之处在于,getCanonicalPath()得到的是一个规范的路径,而getAbsolutePath()是用构造File对象的路径+当前工作目录。例如在上面的例子中.(点号)代表当前目录。getCanonicalPath()就会把它解析为当前目录但是getAbsolutePath()会把它解析成为目录名字(目录名字是点号)。

下面是上面程序在我电脑上的输出:

G:xhuojkonw.srcbaidu

G:xhuojkonwsrcbaidu

3. java读取文件路径

你的头是e://tttt11.PNG不是e://tttt11//1.PNG???如果头是e://tttt11//1.PNG,filepath没有用,去掉。

这段这么改:for (i=0; i <= str.length(); i += 2) { if (i == str.length() - 1 || i == str.length() - 2) break; else fileName = str.substring(i); } // System.out.println(filePath); if(ii!=100) fileName = str.substring(i);。

..后面不改.如果头是e://tttt11.PNG,那这个和下面的循环规律不一样,大概写下:if(ii==1)filePath=".PNG";把我上面修改后的代码加到else里就行了(用我上面修改后的代码,不然你的尾还是显不出来)。

4. java 如何获取文件路径

public void doGet(HttpServletRequest request ,HttpServletResponse response )

throws ServletException ,IOException{

OutputStream out;//输出响应正文的输出流

InputStream in; //读取本地文件的输入流

//获取filename 请求参数

String filename =requeset.getParameter("filename");

if(filename==null){

out=response.getOutputStream();

out.write("please input filename.".getBytes());

out.close;

return;

}

//获得读取本地文件的输入流

in=getServletContext().getResourceAsStream("/store"+filename);

int length=in.available();

}

5. java怎么通过文件的路径读取文件

package file.system.demo.exception;

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class ReadFile {

public static String getFile(String realpath) {

Scanner scanner = null;

String text = "";

try {

File file= new File(realpath);

scanner = new Scanner(file);

} catch (FileNotFoundException e) {

e.printStackTrace();

}

if(scanner!=null){

while(scanner.hasNextLine()){

text+=scanner.nextLine();

}

scanner.close();

}

//System.out.println(text);

return text;

}

static class InnerTest{

public static void main(String[] args) {

String realpath = "D:test.txt";

String text=getFile(realpath);

System.out.println(text);

}

}

}

实现方式有很多,还可以用字节流FileInputStream,字符流FileReader等方式读取

TAG标签:#文件 #读取 #java #路径 #