java读取同目录下的txt文件

如下图,读取相同目录下的txt文件


java读取同目录下的txt文件_第1张图片

​
public class TestHelper {
	public static JSONObject readTXT() {
		JSONObject obj = new JSONObject();
		String path = new TestHelper().getPath() + "test.txt";
		path = path.replace("file:/", "");
		path = path.replace("/", "//");
		File file = new File(path);
		StringBuilder sb = new StringBuilder("");
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String l = null;
			while ((l = br.readLine()) != null) {
				sb = sb.append(l);
			}
			String str = sb.toString();
			// System.out.println(str);
			obj = JSONObject.parseObject(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
}

​

 

 private String getPath(){
       return TestHelper.class.getResource("").toString();
    }

 

 

 

 

 

 

你可能感兴趣的:(工具类)