获取文件路径相关

String path = this.getClass().getClassLoader().getResource("").getPath();
System.out.println("path="+path); // path=/D:/java/workspace-idea/kafka-test-demo/target/classes

String path = this.getClass().getClassLoader().getResource("mybatis/test.xml").getPath();
System.out.println("path="+path); // path=/D:/java/workspace-idea/kafka-test-demo/target/classes/mybatis/test.xml



@RequestMapping("testdemo")
public String testdemo()throws Exception{
String path = this.getClass().getClassLoader().getResource("").getPath();
System.out.println("path="+path);
File file = new File(path+"mybatis/test.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
for(int i=0;i<5;i++){
fw.write("我就是测试一下啦啦啦,num="+i+",\r\n");
fw.flush();
}
System.out.println("写数据成功啦!!!");
fw.close();

StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(file));
String s = null;
while((s=reader.readLine()) != null){
sb.append(System.lineSeparator()+s);
}
reader.close();
System.out.println(sb.toString());
return "ok";

}
posted @ 2022-03-23 14:49  java_my_skill  阅读(47)  评论(0)    收藏  举报