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



我想在新文件中写入的这个程序的输出。我如何生成像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
        }
    }

使用此代码将输出写入新的文本文件。。。这能帮你吗

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();
    }
   }
   }

相关内容

  • 没有找到相关文章

最新更新