创建文件

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

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

读取文件

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();

写文件

  • 追加

    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();
    }
  • 覆盖

    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();
    }

文件大小

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];
}

获取属性值

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;
}