如题,怎么做
读取resource/txt 目录下file.txt 文件
献上代码
public class FileUtil {
public static String getFileContent(String str) throws IOException{
//找到要读取目标文件的地址
String path = FileUtil.class.getClassLoader().getResource(str).getPath();
File file = new File(path);
FileReader fileReader = new FileReader(file);
Reader reader = new InputStreamReader(new FileInputStream(file),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while((ch = reader.read()) != -1){
sb.append((char)ch);
}
fileReader.close();
reader.close();
return sb.toString();
}
public static void main(String[] args) throws IOException {
System.out.println(getFileContent("txt/file.txt"));
}
}
运行结果
结束了,又水了一篇文章。