每次使用Java运行程序时,如何创建新文件

时间:2017-09-02 09:53:25

标签: java xml csv

下面是我处理过的代码,它基本上遍历文件夹并从xml文件中提取数据并将数据输出到CSV文件中。所有这一切都有效。但我想每次运行程序时都创建新的输出csv文件。如果你们能提供一些例子或修改我所使用的代码,我将不胜感激。我现在一直试图找出解决方案。

public class MergeCode1 {

    public void walk(String path,Boolean is_parent) throws Exception {
        File filePath = new File ("C:/Users/Vishvesh Savant/Desktop/Mirriad/");
        System.out.println(filePath);


        File root = new File(path); //Input File Path
        File[] list = root.listFiles();

        while(is_parent == false);
        {
            Random rand = new Random();
            int value;
            value=rand.nextInt(50)+1;
            filePath = new File (("C:/Users/Vishvesh Savant/Desktop/Mirriad/"+"new_one"+value+".csv"));
        }
        try{
            if (list == null) return;
            System.out.println("2");

            for (File f : list ) {
                DocumentBuilderFactory dbfactory = null;
                DocumentBuilder dbuilder = null;
                Document doc = null;

                if (f.isDirectory()) {
                    walk(f.getPath(),false);
                    System.out.println( "Dir:" + f.getAbsolutePath());
                }
                else {
                    System.out.println( "File:" + f.getAbsolutePath());
                    dbfactory = DocumentBuilderFactory.newInstance();
                    dbuilder = dbfactory.newDocumentBuilder();
                    doc =  dbuilder.parse(f.getAbsolutePath());
                    doc.getDocumentElement().normalize();

                    NodeList list1 = doc.getElementsByTagName("product");                   
                    FileWriter fileWriter = new FileWriter(filePath, true);

//                  String Fileheader="uid,title";
//                  fileWriter.append(Fileheader.toString());
//                  fileWriter.append("\n");

                    for(int i=0; i<list1.getLength();i++){
                        Node node = list1.item(i);
                        if(node.getNodeType() == Node.ELEMENT_NODE){
                            Element element = (Element) node;
                            fileWriter.append(element.getAttribute("uid"));
                            System.out.println(element.getAttribute("uid"));
                            fileWriter.append(",");
                            fileWriter.append( element.getElementsByTagName("title").item(0).getTextContent());
                            System.out.println(element.getElementsByTagName("title").item(0).getTextContent());
                            fileWriter.append(",");
                            fileWriter.append( element.getElementsByTagName("actor").item(0).getTextContent());
                            System.out.println(element.getElementsByTagName("actor").item(0).getTextContent());
                            fileWriter.append(",");
                            fileWriter.append( element.getElementsByTagName("director").item(0).getTextContent());
                            System.out.println(element.getElementsByTagName("director").item(0).getTextContent());
                            fileWriter.append(",");
                            fileWriter.append( element.getElementsByTagName("country").item(0).getTextContent());
                            System.out.println(element.getElementsByTagName("country").item(0).getTextContent());
                            fileWriter.append(",");
                            fileWriter.append( element.getElementsByTagName("format").item(0).getTextContent());
                            System.out.println(element.getElementsByTagName("format").item(0).getTextContent());
                            fileWriter.append(",");
                            fileWriter.append( element.getElementsByTagName("bitrate").item(0).getTextContent());
                            System.out.println(element.getElementsByTagName("bitrate").item(0).getTextContent());
                            fileWriter.append(",");
                            fileWriter.append( element.getElementsByTagName("fps").item(0).getTextContent());
                            System.out.println(element.getElementsByTagName("fps").item(0).getTextContent());
                            fileWriter.append(",");
                            fileWriter.append( element.getElementsByTagName("aspect").item(0).getTextContent());
                            System.out.println(element.getElementsByTagName("aspect").item(0).getTextContent());
                            fileWriter.append(",");
                            fileWriter.append( element.getElementsByTagName("width").item(0).getTextContent());
                            System.out.println(element.getElementsByTagName("width").item(0).getTextContent());
                            fileWriter.append(",");
                            fileWriter.append(element.getBaseURI());
                            fileWriter.append(element.getAttribute("uid"));
                            fileWriter.append(element.getElementsByTagName("format").item(0).getTextContent());

                            fileWriter.append("\n");

                            //fileWriter.flush();
                            fileWriter.close();
                        }
                    }
                }
            }
        }
        catch (Exception e) {
            System.out.println("Error!!!");
            e.printStackTrace();
        }
    }

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

        MergeCode1 fw = new MergeCode1();
        fw.walk("C:/Users/Vishvesh Savant/Desktop/Mirriad/Test",true);  
    }
}

4 个答案:

答案 0 :(得分:2)

而不是这一行:

filePath = new File (("C:/Users/Vishvesh Savant/Desktop/Mirriad/"+"new_one"+value+".csv"));

您可以使用:

File filePath = File.createTempFile("out_", ".csv", new File("C:/Users/Vishvesh Savant/Desktop/Mirriad/"));

这将生成给定目录中的uniqe文件名,前缀为“out_”,后缀为“.csv”。

答案 1 :(得分:0)

使用System.currentTimeMillis()

long value;
value = System.currentTimeMillis();

答案 2 :(得分:0)

我理解你的方式,你想把一个电话的所有记录从主要走到同一个文件;这样做的方法是在walk方法之外创建CSV的filePath(在main的情况下)并将方法签名更改为:

public void walk(String path,Boolean is_parent, String filePath) throws Exception {

然后你的所有通话都有相同的文件名 - 也适用于你的子目录...假设你也将它传递给反射通话(我相信这是你的意图 - 对吗?)

答案 3 :(得分:0)

使用“Create”函数存储值,然后在Main方法中附加该值。每次在程序运行时都会通过创建带有记录的新csv文件来调用Create。

//start activity indicator here

    Alamofire.request("https://urlhere.com" , method: .post).validate().responseJSON { response in

        switch response.result {

        case .success(let value):

              if let json = JSON(value) {

               let name = json["name"].stringValue

                //hide activity indicator here

               }
               else
                {
                 //No data returned
                }

        case .failure(let error):
            print(error)
            //show error indicator here

        }

    }