使用Java中的FileWriter进行多次Over写操作

时间:2014-05-18 12:48:53

标签: java csv filewriter

我试图读取包含股票价格数据的N个不同的CSV文件。我想从每个文件中提取一个特定列,并在单个CSV文件中显示这些列。

问题是组合文件只包含我作为输入提供的第一个文件中的写入数据,即在循环的迭代中数据没有被覆盖。

有人可以帮忙吗?或者建议一种新方法?

            public static void main(String[] args) throws IOException
        {

    int filecount=0;
    System.out.println("Enter Number of Files");
    Scanner stream =new Scanner(new InputStreamReader(System.in));
     filecount= Integer.parseInt(stream.next());

    File file2 = new File("Combined_Sym.csv");
    FileWriter fwriter= new FileWriter("Combined_Sym.csv",true);
    PrintWriter outputFile= new PrintWriter(fwriter);
    int i;
    for(i=0;i<filecount;i++)
    {
    System.out.println("Enter File name "+i);
    String fileName =stream.next();
    File file = new File(fileName);

    Scanner inputStream = new Scanner(file);
    Scanner inputStream2= new Scanner(file2);

    if(!inputStream2.hasNext()){
    outputFile.println(fileName);
    }
    else
    {       String header=inputStream2.next();
    System.out.println(header+","+fileName);
        outputFile.println(header+","+fileName);
    }

    while(inputStream.hasNext())
    {
    String data= inputStream.next();
    String[] values = new String[8];
    values = data.split(",");
    String sym=values[7];

    if(!inputStream2.hasNext())
    outputFile.println(sym);
    else
    {
        String data2= inputStream2.next();
    outputFile.println(data2+","+sym);
    System.out.println(data2+","+sym);
    }

    }

    inputStream.close();
    inputStream2.close();
    outputFile.close();

    }

}

}

1 个答案:

答案 0 :(得分:0)

你可以尝试改变:

for(i=0;i<filecount;i++)
{
System.out.println("Enter File name "+i);
String fileName =stream.next();
File file = new File(fileName);

File file;
for(i=0;i<filecount;i++)
{
System.out.println("Enter File name "+i);
String fileName =stream.next();
file = new File(fileName);