讀取一個txt文件,文件中有一個8位的日期(任意),讀出日期並打印此從日期開始的一個月日歷,最好能有詳細代碼和注釋
參考代碼如下:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateCalendar {
public static void main(String[] args) {
printLatestMonth("src/date.txt");
}
public static void printLatestMonth(String filePath){
String fileContent = readFromFile(filePath,null);
if(fileContent==null||fileContent.length()<8){
System.out.println("日期格式不正確,請保證日期格式為yyyyMMdd");
return;
}
DateFormat format = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
try {
Date currentDate = format.parse(fileContent);
calendar.setTime(currentDate);
System.out.println("crurent date is:"+currentDate);
for(int i = 0;i<30;i++){
calendar.add(Calendar.DATE, 1);
System.out.println(calendar.getTime());
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String readFromFile(String fileName,String charSet){
if (fileName == null || "".equals(fileName)) {
System.out.println("文件名稱為空...");
return "";
}
// 設置字符編碼
if(charSet==null||charSet.length()==0){
charSet = "UTF-8";
}
File file = new File(fileName);
FileInputStream fin = null;
StringBuffer buffer = new StringBuffer();
try {
fin = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(
fin, charSet));
String content = reader.readLine();
while (content != null) {
buffer.append(content);
// 循環讀取下一行,沒有這行代碼就是死循環的啦。。。
content = reader.readLine();
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return buffer.toString();
}
}
src目錄下文件格式:20160310