这是 .txt 的一部分:
2013 年 3 月 28 日星期四 12:18:28 EDT
内存免费:601836 kB
Linux 2.6.18-308.el5 (CWAPP1.conceptwave.com) 03/28/2013
平均 CPU:%user %nice %system %iowait %steal %idle 0.15 0.00 0.05 0.02 0.00 99.79
=========================
2013 年 3 月 28 日星期四 12:18:38 EDT
内存免费:598312 kB
Linux 2.6.18-308.el5 (CWAPP1.conceptwave.com) 03/28/2013
平均 CPU:%user %nice %system %iowait %steal %idle 0.15 0.00 0.05 0.02 0.00 99.79
=========================
我需要读取日期、可用内存和 %idle,并写入两个包含两列的 csv 文件。一个是日期和内存,另一个是日期和 %idle。所以我编写了读取数据并将其附加到 3 个列表的代码。如何将它们写入 2 个 csv 文件以满足我的要求?
提前致谢。
我的代码:
List<String> dateTime = new ArrayList<String>();
List<String> memFree = new ArrayList<String>();
List<String> pIdle = new ArrayList<String>();
public static void main(String[] args)
{
// TODO Auto-generated method stub
}
public void readFile(String file)
{
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String str = null;
try
{
while((str=br.readLine()) != null)
{
String[] st = str.split("\\s+");
if (st[0] == "MemFree:")
memFree.add(st[1]);
if(isDouble(st))
pIdle.add(st[4]);
if(isDate(str))
{
String subStr = str.substring(0, 15);
dateTime.add(subStr);
}
}
}
finally
{
br.close();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found!");
}
catch(IOException e)
{
System.out.println(e);
}
}
public boolean isDate(String str)
{
DateFormat df = new SimpleDateFormat("E M d");
try
{
String subStr = str.substring(0, 8);
@SuppressWarnings("unused")
Date currentDate = df.parse(subStr);
return true;
}
catch(ParseException e)
{
return false;
}
}
public boolean isDouble(String[] st)
{
try
{
for (int i = 0; i < st.length;)
{
@SuppressWarnings("unused")
double num = Double.parseDouble(st[i]);
return true;
}
}
catch(IllegalArgumentException ex)
{
return false;
}
return false;
}
public void writeToCSV(List<String> dateTime, List<String> memFree, List<String> pIdle)
{
//UNFINISHED - NEED HELP!
String dateSepVal = "";
if(dateTime != null && memFree != null)
{
Iterator<String> iter = dateTime.iterator();
while(iter.hasNext())
{
dateSepVal += iter.next() + ",";
}
if(dateSepVal.endsWith(","))
{
dateSepVal = dateSepVal.substring(0, dateSepVal.lastIndexOf(","));
}
}
if(dateTime != null && pIdle !=null)
{
//TODO
}
}