面试题: 怎么把系统时间写入文件中?
面试遇到这样一个问题
1. 怎么把系统当前时间写入文件中?
按这个格式 yyyy-MM-dd HH:mm:ss
2. 怎么读这个文件把它解析成一个DATE类型
[解决办法]
import java.io.*;import java.util.*;import java.text.*;public class DateInFile{ public static void main(String[] args){ File file = new File("D:/train/csdn/date.txt"); try{ BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\train\\csdn\\date.txt")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d = new Date(); String msg = sdf.format(d); bw.write(msg); bw.flush();System.out.println(msg+"已写入文件!"); bw.close(); BufferedReader buf = new BufferedReader(new FileReader("D:\\train\\csdn\\date.txt")); String s = buf.readLine(); Date dd = sdf.parse(s);System.out.println(dd+"已从文件取出!"); buf.close(); } catch(Exception e){ e.printStackTrace(); } }}
[解决办法]
只是把当前日期取出,然后格式化成特定形式的字符串,
然后就是IO操作。
[解决办法]
楼上朋友回答的不错,楼主参考一下
[解决办法]
mark
[解决办法]
WriteIniData("Now", "datetime", riqi, path);
Console.WriteLine();
Console.WriteLine(ReadIniData("Now", "datetime", "", path));
Console.ReadLine();
}
[DllImport("kernel32")]//返回0表示失败,非0为成功
private static extern long WritePrivateProfileString(string section, string key,
string val, string filePath);
[DllImport("kernel32")]//返回取得字符串缓冲区的长度
private static extern long GetPrivateProfileString(string section, string key,
string def, StringBuilder retVal, int size, string filePath);
// 写入*.ini文件
public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
{
if (File.Exists(iniFilePath))
{
long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
if (OpStation == 0)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
// 读取*.ini文件中的相应节下面的键值
public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
{
if (File.Exists(iniFilePath))
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
return temp.ToString();
}
else
{
return String.Empty;
}
}
}
}