java 之 classpath下文件路径

时间:2022-03-20 15:21:14
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;


public class ClassPathTest {

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//找得到
File file = new File("bin/com/ethan/test/readme.txt");
String path = file.getAbsolutePath();
System.out.println(file.getAbsolutePath());

// FileInputStream fis = new FileInputStream(new File(path));
// InputStream is = ClassPathTest.class.getClassLoader().getResourceAsStream("com/ethan/test/readme.txt");

//DataOutputStream 先writeUTF写入内容和内容长度,才可以用readUTF读出来。
InputStream is = ClassPathTest.class.getResourceAsStream("com/ethan/test/readme.txt");
DataInputStream dis = new DataInputStream(is);
byte[] buf = new byte[4096];
int len = dis.read(buf);
System.out.println(new String(buf,0,len));
is.close();
}

}