avatar

目录
File 工具类的常用方法

创建文件

判断文件夹是否存在,不存在则创建

java
1
2
3
4
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}

读取文件

java
1
2
3
4
5
6
7
8
9
10
11
File file = new File(filePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String row;
while ((row = reader.readLine()) != null) {
System.out.println(row);
}

// 删除文件
file.delete();

reader.close();

写文件

  • 追加

    java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    try {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
    writer.write(content + "\t\n");
    writer.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
  • 覆盖

    java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    try {
    File file = new File("src/main/resources/application.properties");
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
    writer.write(text);
    writer.close();
    return null;
    } catch (Exception e) {
    e.printStackTrace();
    }

文件大小

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
readableFileSize(file.length())

/**
* 文件大小转换
* @param size
* @return
* @author muycode
*/
private String readableFileSize(long size) {
if (size <= 0) return "0";
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}

获取属性值

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static String getProperty(String configProperties, String key) {
try {
ResourceBundle resource = ResourceBundle.getBundle(configProperties);
return resource.getString(key);
} catch (Exception e) {
e.printStackTrace();
}
try {

} catch (Exception e) {
e.printStackTrace();
}
return null;
}
文章作者: 颜不喜
文章链接: https://www.muycode.cn/article/file20200318.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 颜不喜
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论