https://blog.csdn.net/my__sun_/article/details/74450241

读取文件的写法,相对路径

在当前的目录结构中读取test.txt的有四种写法

  • 简单粗暴的 File file = new File(“src/test.txt”)
  • 使用类的相对路径
  • 使用当前线程的类加载器
  • 读取web工程下的文件 使用getRealPath()读取

File file = new File("src/test.txt");
File file = new File(TestRelativePath.class.getResource("/test.txt").getFile());
File file = new File(Thread.currentThread().getContextClassLoader().getResource("test.txt").getFile());
File file = new File(getServletContext().getRealPath("/WEB-INF/classes/test.txt"));

下面我来一一介绍:

简单粗暴的 File file = new File(“src/test.txt”);

  @Test
/**
* 这种方法 “” 空代表的是 这个Java项目 TestSomeTechnology 由于实际项目在打包后没有src目录 所以这种方法不常用
*/
public void testMethod1() throws IOException{
File file = new File("src/test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String len = null;
while ((len=br.readLine())!=null){
System.out.println(len);
}
}

使用类的相对路径

TestRelativePath.class.getResource(“/test.txt”).getFile()

 @Test
/**
* 使用类的相对路径
* 这种方法 “/” 代表的是bin。 src文件夹和resources 文件夹下的的东西都会被加载到bin下面 因为这两个文件被配置为了source
*/
public void testMethod2() throws IOException{ File file = new File(TestRelativePath.class.getResource("/test.txt").getFile());
BufferedReader br = new BufferedReader(new FileReader(file));
String len = null;
while ((len=br.readLine())!=null){
System.out.println(len);
}
}

使用当前线程的类加载器

Thread.currentThread().getContextClassLoader().getResource(“test.txt”).getFile()

@Test
/**
* 这种是通过当前线程的类加载器
* 这种方法 “ ” 空代表的是bin 。 于是就直接填写test,文件夹下的的东西都会被加载到bin下面,因为这两个文件被配置为了source
*/
public void testMethod3() throws IOException{ File file = new File(Thread.currentThread().getContextClassLoader().getResource("test.txt").getFile());
BufferedReader br = new BufferedReader(new FileReader(file));
String len = null;
if ((len=br.readLine())!=null){
System.out.println(len);
}
}

读取web工程下的文件 使用getRealPath()读取

目录如下 :

读取 index.jsp

@WebServlet(name = "TestServlet",urlPatterns = "/TestServlet")
public class TestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
} /**
* web工程的根目录是 webRoot, 使用 “/” 代表webroot webroot下面有index.jsp文件
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File file = new File(getServletContext().getRealPath("/index.jsp"));
BufferedReader br = new BufferedReader(new FileReader(file));
String len = null;
while ((len=br.readLine())!=null){
System.out.println(len);
}
}
}

读取 test.txt文件 
不过如果想读取test.txt 的话 我们可用用上面的方式

 File file = new File(Thread.currentThread().getContextClassLoader().getResource("test.txt").getFile());

也可以使用 getRealPath() 
不过由于是以 webroot为根目录 我们需要从classes里面读:idea的classes等价于esclipse的classpath 。classes说明:

代码:

File file = new File(getServletContext().getRealPath("/WEB-INF/classes/test.txt"));

getResourceAsStream()方法详解

getResourceAsStream()用法与getResouce()方法一样的,用getResource()取得File文件后,再new FileInputStream(file) 与 getResourceAsStream() 的效果一样。。

两个代码效果一样

InputStream inputStream1 = new FileInputStream(new File(Thread.currentThread().getContextClassLoader().getResource("test.txt").getFile()));
InputStream inputStream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.txt");

java中使用相对路径读取文件的写法总结 ,以及getResourceAsStream() (转)的更多相关文章

  1. Java FileReader使用相对路径读取文件

    Java FileReader使用相对路径读取文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 在进行编程时需要时常更换主机进行测试,如果使用绝对路径则需要经常更改,为此使用相对路径是一个 ...

  2. java中的IO流读取文件

    1 InputStream类和OutputStream类 InputStream.read()方法从文件中读取一个字节(0-255),然后将此字节转换成对应的整数返回.假设一个文件的编码为utf-8编 ...

  3. java 使用相对路径读取文件

    java 使用相对路径读取文件 1.java project环境,使用java.io用相对路径读取文件的例子: *目录结构:  DecisionTree            |___src      ...

  4. java中的绝对路径和相对路径

    1.基本概念的理解 绝对路径:绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(URL和物理路径)例如:C:/xyz/test.txt 代表了test.txt文件的绝对路径.http://www ...

  5. C# Note5:使用相对路径读取文件

    一.C#中使用相对路径读取配置文件 一般Solution的目录结构如下图所示: (如过看不到某些文件,可以点击 “显示所有文件” 图标) 方法一:由于生成的exe文件在bin\debug目录下,可以使 ...

  6. Java中使用HttpPost上传文件以及HttpGet进行API请求(包含HttpPost上传文件)

    Java中使用HttpPost上传文件以及HttpGet进行API请求(包含HttpPost上传文件) 一.HttpPost上传文件 public static String getSuffix(fi ...

  7. Java相对路径读取文件

    不管你是新手还是老鸟,在程序中读取资源文件总会遇到一些找不到文件的问题,这与Java底层的实现有关,不能算bug,只要方法得当,问题还是可以解决的. 项目的文件夹结构: repathtest ├─sr ...

  8. C#中winform使用相对路径读取文件的方法

    http://cache.baiducontent.com/c?m=9f65cb4a8c8507ed4fece763105392230e54f73b6cd0d3027fa3cf1fd579080101 ...

  9. web项目中从不同的路径读取文件

    项目中的配置文件可以放在classpath下,webapp下获取其他任何一个指定的绝对地址,读取这些文件就从这三个地方去找.主要代码如下: private List<String> get ...

随机推荐

  1. NAT模式

    NAT NAT模式中,就是让虚拟机借助NAT(网络地址转换)功能,通过宿主机器所在的网络来访问公网. NAT模式中,虚拟机的网卡和物理网卡的网络,不在同一个网络,虚拟机的网卡,是在vmware提供的一 ...

  2. 【keytool jarsigner工具的使用】Android 使用JDK1.7的工具 进行APK文件的签名,以及keystore文件的使用

    一个android apk的编译过程 请参考: http://www.2cto.com/kf/201312/261475.html 典型的编译过程: aapt( Android Asset Packa ...

  3. Java NIO Channel to Channel Transfers

    In Java NIO you can transfer data directly from one channel to another, if one of the channels is a ...

  4. 混沌分形之迭代函数系统(IFS)

    IFS是分形的重要分支.它是分形图像处理中最富生命力而且最具有广阔应用前景的领域之一.这一工作最早可以追溯到Hutchinson于1981年对自相似集的研究.美国科学家M.F.Barnsley于198 ...

  5. 8Manage PMP 项目管理工具

    范围与需求管理 8Manage 项目管理平台提供先进的机制集中管理项目的范围与需求: 提供需求申请功能:获取,过滤,解析和明确项目的需求 提供需求矩阵功能:整理分析需求并跟踪需求从开始到完成的整个过程 ...

  6. libnids

    一.简介 libnids的英文意思是 Network Intrusion Detect System library,即网络入侵监测系统函数库.它是在前面介绍的两种C函数接口库libnet和libpc ...

  7. solr建立pdf/word/excel索引的方法

    PS: 本文假设你已经成功的搭建了一个Solr服务器步骤如下:(1)准备好一份Solr的源码,假设现在保存在c:\apache-solr-1.4.1\目录下(2)从https://issues.apa ...

  8. [leetcode]Reverse Words in a String @ Python

    原题地址:https://oj.leetcode.com/problems/reverse-words-in-a-string/ 题意: Given an input string, reverse ...

  9. [leetcode]Permutations II @ Python

    原题地址:https://oj.leetcode.com/problems/permutations-ii/ 题意: Given a collection of numbers that might ...

  10. Android -- 混淆

    混淆本质 把原来有具体含义的类名,变量名,方法名,修改成让人看不懂的名字,例如方法名getxx混淆为方法名a. Android Studio中的混淆 Android工程目录下有个文件,proguard ...