您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要讲解了“Java怎么实现读取项目中的文件”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Java怎么实现读取项目中的文件”吧!
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.76</version> </dependency>
重点部分
. /代表同级目录
…/ 代表上级目录(两个点)
/ 代表根目录
public class FileService {
public JSONObject reader(){
JSONObject resultJson = null;
String file = "src/main/resources/config_dev.json";
InputStream is = null;
try {
is = new FileInputStream(file);//操作
byte[] bytes = new byte[5000];//数组容量超级大,一次能将中英混合文本全部读取完
int len = -1;
while ((len = is.read(bytes)) != -1) {
String str = new String(bytes, 0, len, "UTF-8");
resultJson = process(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {//释放资源
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultJson;
}
private static JSONObject process(String content) {
JSONObject json = JSONObject.parseObject(content);
return json;
}
} public static String reader(String filePath) {
try {
File file = new File(filePath);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = bufferedReader.readLine();
while (lineTxt != null) {
return lineTxt;
}
}
} catch (UnsupportedEncodingException | FileNotFoundException e) {
System.out.println("Cannot find the file specified!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Error reading file content!");
e.printStackTrace();
}
return null;
} public void readPropertiesFile() {
Properties pro = new Properties();
InputStream is = this.getClass().getResourceAsStream("/application.properties");
try {
pro.load(is);
Enumeration en = pro.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = pro.getProperty(key);
System.out.println(key + "--" + value);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <link rel="stylesheet" href="https://qxhut.cn/zb_users/plugin/Jz52_click/click.css"> <script src="https://qxhut.cn/zb_users/plugin/Jz52_click/click.js"></script> <h2>Click Style</h2> </body> </html>
感谢各位的阅读,以上就是“Java怎么实现读取项目中的文件”的内容了,经过本文的学习后,相信大家对Java怎么实现读取项目中的文件这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。