package com.tom;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestF {
public static void main(String[] args) throws IOException {
//"." :当前project的路径
File file0 = new File("./1.txt");
System.out.println(file0.exists());
File file01 = new File("1.txt");
System.out.println(file01.exists());
String filePath = "./"+"bulk"+"/"+"abc.xls";
File file = new File(filePath);
file.getParentFile().mkdirs();
try {
file.createNewFile();
System.out.println("successfully create files!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file2 = new File("abc/2.txt");
System.out.println(file2.exists());
File file21 = new File("./abc/2.txt");
System.out.println(file21.exists());
File file3 = new File("./src/3.txt");
System.out.println(file3.exists());
//src目录下的文件会被编译到bin目录
File file4 = new File("./bin/3.txt");
System.out.println(file4.exists());
File file5 = new File("bin/3.txt");
System.out.println(file5.exists());
//但是bin是classpath,所以可以这么读取
//"/"代表classpath,绝对路径
String f = TestF.class.getResource("/4.txt").getPath();
System.out.println(f);
//不以"/"开头,则认为是从当前类所在路径上3层开始读取
String f1 = TestF.class.getResource("../../4.txt").getPath();
System.out.println(f1);
//和当前类在同一个包里,用绝对路径读取
String f2 = TestF.class.getResource("/com/tom/5.txt").getPath();
System.out.println(f2);
//用相对路径读取
String f21 = TestF.class.getResource("5.txt").getPath();
System.out.println(f21);
//读取子包下面的7.txt
String f22 = TestF.class.getResource("/com/tom/jimi/7.txt").getPath();
System.out.println(f22);
String f23 = TestF.class.getResource("jimi/7.txt").getPath();
System.out.println(f23);
String f3 = TestF.class.getClassLoader().getResource("com/tom/6.txt").getPath();
System.out.println(f3);
String f4 = TestF.class.getClassLoader().getResource("4.txt").getPath();
System.out.println(f4);
File file7 = new File("./bin/com/tom/jimi/7.txt");
System.out.println(file7.exists());
File file8 = new File("./src/com/tom/jimi/7.txt");
System.out.println(file8.exists());
System.out.println(readFile("5.txt"));
System.out.println(readFile("jimi/7.txt"));
System.out.println(readFile("/com/kao/8.txt"));
}
public static String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(TestF.class.getResourceAsStream(fileName)));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
}
</pre><pre name="code" class="java"><img src="https://img-blog.csdn.net/20141125233533765" alt="" />