这是.txt的一部分:
Linux 2.6.18-308.el5(CWAPP1.conceptwave.com)03/28/2013
avg-cpu:%user%nice%system%iowait%steal%idle 0.15 0.00 0.05 0.02 0.00 99.79
========================
Linux 2.6.18-308.el5(CWAPP1.conceptwave.com)03/28/2013
avg-cpu:%user%nice%system%iowait%steal%idle 0.15 0.00 0.05 0.02 0.00 99.79
========================
我需要读取日期,内存空闲和%空闲,并写入两个包含两列的csv文件。一个是日期和内存,另一个是日期和%空闲。所以我编写了读取数据的代码并将其附加到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
}
}
答案 0 :(得分:0)
写入文件就像阅读一样,反过来说:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("delete.me"))) {
writer.write("something");
writer.newLine();
}
如果您想为每个提取的日期添加一个新行&amp;内存值,它可能看起来像这样:
public void writeToCSV(List<String> dateTime, List<String> memFree) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("delete.me"))) {
if(dateTime == null || memFree == null)
return;
Iterator<String> memFrees = memFree.iterator();
for (String dt: dateTimes) {
if (!memFrees.hasNext())
return;
writer.write(dt + "," + memFrees.next());
writer.newLine();
}
}
}
但正如 M Sach 建议的那样,您可能希望看一下这样的框架。