使用缓冲区写入器在新文件中写入输出

时间:2015-04-07 09:57:05

标签: file stream filestream streamwriter filewriter

这个程序的输出我想在新文件中写。所以如何生成像xls这样的新文件。或其他,并将结果写入其中。 我已经读过文件,然后应用kmean聚类算法并生成输出,现在我想写一下。

 package kmean;
    //package greenblocks.statistics;

    import java.io.IOException;



    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;

    import weka.clusterers.SimpleKMeans;
    import weka.core.Instances;

    /**
     *
     * @author admin
     */
    public class Kmean {

            public static BufferedReader readDataFile(String filename) {
            BufferedReader inputReader = null;

            try {
                inputReader = new BufferedReader(new FileReader(filename));
            } catch (FileNotFoundException ex) {
                System.err.println("File not found: " + filename);
            }

            return inputReader;
        }


        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws IOException, Exception {

            SimpleKMeans kmeans = new SimpleKMeans();

            kmeans.setSeed(10);

            //important parameter to set: preserver order, number of cluster.
            kmeans.setPreserveInstancesOrder(true);
            kmeans.setNumClusters(5);

            BufferedReader datafile = readDataFile("elecNormNew.arff"); 
                   // BufferedReader datafile = readDataFile("perturbed.csv"); 
            Instances data = new Instances(datafile);


            kmeans.buildClusterer(data);

            // This array returns the cluster number (starting with 0) for each instance
            // The array has as many elements as the number of instances
            int[] assignments = kmeans.getAssignments();

            int i=0;
            for(int clusterNum : assignments) {
                System.out.printf("Instance %d -> Cluster %d \n", i, clusterNum);
                i++;
            }

            // TODO code application logic here
        }
    }

1 个答案:

答案 0 :(得分:0)

使用此代码在新文本文件中编写输出...这可能会对您有所帮助

包com.mkyong;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
public static void main(String[] args) {
    try {

        String content = "This is the content to write into file";

        File file = new File("/filePath/filename.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }
   }
   }