IO 文本操作記錄
1、判斷文本目錄或者文件是否存在,如不存在,可以進(jìn)行創(chuàng)建dir1.mkdir();刪除file.delete();
1 File dir = new File(TXTPATH); // TXTPATH 可以是一個(gè)目錄或者一個(gè)文件的路徑。
2 if (!dir.exists()) {
3 flag = false;
4 if (logger4onln.isInfoEnabled()) {
5 logger4onln
6 .info("[readtxtfile] the file directory isn't exist. ");
7 }
8 return;
9 }
2 if (!dir.exists()) {
3 flag = false;
4 if (logger4onln.isInfoEnabled()) {
5 logger4onln
6 .info("[readtxtfile] the file directory isn't exist. ");
7 }
8 return;
9 }
2、 獲取該目錄下的文件名
String[] filename = dir.list();// 獲取該目錄下的文件名,形成一個(gè)數(shù)組
for (int i = 0; i < filename.length; i++)
{
//do something 可以通過遍歷每個(gè)文件名,進(jìn)行處理
}
for (int i = 0; i < filename.length; i++)
{
//do something 可以通過遍歷每個(gè)文件名,進(jìn)行處理
}
3、這里順便記錄一個(gè)獲取日期的方法:
1 Calendar calendarYest = Calendar.getInstance(); // 前一天的日期時(shí)間
2 calendarYest.add(Calendar.DATE, -1); //將當(dāng)前時(shí)間的日 減一天。 通過//calendarYest.setTimeZone(new Date().getTime()) 來設(shè)置一個(gè)自定義時(shí)間。
3 int month = calendarYest.get(Calendar.MONTH); //獲取月份
2 calendarYest.add(Calendar.DATE, -1); //將當(dāng)前時(shí)間的日 減一天。 通過//calendarYest.setTimeZone(new Date().getTime()) 來設(shè)置一個(gè)自定義時(shí)間。
3 int month = calendarYest.get(Calendar.MONTH); //獲取月份
4、通過正則表達(dá)式判斷文件名格式是否正確
Pattern pattern = Pattern.compile("" + KEY_FILE_NAME
+ "\\d{10}"); //這里的key_file_name是一種文本命名的固定格式
Matcher matcher = pattern.matcher(fileName);
if (matcher.find())
{
//do something.
}
+ "\\d{10}"); //這里的key_file_name是一種文本命名的固定格式
Matcher matcher = pattern.matcher(fileName);
if (matcher.find())
{
//do something.
}
5、一個(gè)移動(dòng)文本的方法
1 /**
2 * 移動(dòng)文本方法
3 */
4 public static boolean removeTo(String from, String to, String fileName) {
5 File file = new File(from, fileName);
6 if (file.isFile()) {
7 file.renameTo(new File(to, file.getName()));
8 return true;
9 }
10 return false; // 移動(dòng)失敗
11 }
2 * 移動(dòng)文本方法
3 */
4 public static boolean removeTo(String from, String to, String fileName) {
5 File file = new File(from, fileName);
6 if (file.isFile()) {
7 file.renameTo(new File(to, file.getName()));
8 return true;
9 }
10 return false; // 移動(dòng)失敗
11 }
6、案例:需要每小時(shí)生成一個(gè)文本記錄,以小時(shí)為單位,超過一小時(shí)生成另外一個(gè)文本



















posted on 2012-05-21 11:43 japper 閱讀(368) 評(píng)論(0) 編輯 收藏 所屬分類: Java