有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将结果保存到txt文件而不使用打印行?

对java完全陌生,有一场噩梦!我有一个235886个单词的列表。txt,我已经设法按升序排序,但是运行它需要一辈子的时间,所以我在想是否可以将结果保存到txt文件中。我该怎么办

感谢所有的帮助。 干杯

public class Main {
static final int NUMWORDS = 235886;
static final String FILENAME = "shuffled.txt";

public static void main(String[] args) {
    String[] words = readWords(FILENAME, NUMWORDS);
    String[] myStringArray = readWords(FILENAME, NUMWORDS);
    sortedWords(words);
}

// 5. Write code to build a sorted version of the list (in ascending order) 
public static void sortedWords(String unsorted[]) {
    sort(unsorted);

    for (int n=0 ;  n <  unsorted.length; n++ ) {
        System.out.println(unsorted[n]);
        // return unsorted;
    }

}static void sort(String[] unsorted){

    for (int i =0; i< unsorted.length; i += 1) {
        int j = findMinIndex(unsorted, i + 1, i);
        if (j != -1) {
            swap(unsorted, i, j);
        }
    }
}

static int findMinIndex(String[] numbers, int startIndex, int minIndex) {
    if (numbers.length <= startIndex) {
        return -1;
    }
    for (int i=startIndex; i < numbers.length; i += 1){
        if (numbers[i].length() > numbers[minIndex].length()){
            minIndex = i;
        }
    }
    return minIndex;
}
static void swap(String[] numbers, int i, int j) {
    String tmp = numbers[i];
    numbers[i] = numbers[j];
    numbers[j] = tmp;
}


private static String[] readWords (String filename,int count){
    String[] words = new String[count];

    try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
        int i = 0;
        for (String line; (line = br.readLine()) != null && i < count; ) {
            words[i++] = line;
        }
    } catch (java.io.IOException e) {
        System.err.println("File: " + filename + " could not be found.");
    }
    return words;
}
}

共 (3) 个答案

  1. # 1 楼答案

    “将结果保存到txt文件。”这就是如何放置String[] words数组中的每一个元素

    import java.io.FileWriter;
    
    String[] words; //Imagine this has a lot of data inside
    try {
       FileWriter writer = new FileWriter("output.txt"); 
       for(String str: words) {
         writer.write(str);
         writer.write("\n");
       }
       writer.close();
    }
    catch (Exception e)
    {
      System.out.println("EXCEPTION: " + e);
    }
    
  2. # 2 楼答案

    您可以将方法sortedWords更改为此方法(需要Java 8或9):

    public static void sortedWords(String unsorted[]) throws FileNotFoundException {
        sort(unsorted);
    
        try(PrintWriter out = new PrintWriter("sorted_words.txt")) {
            Arrays.stream(unsorted).forEach(out::println);
        }
    
    }
    

    这应该可以做到,而且相对简单。以下是支持UTF-8以支持更广泛字符范围的替代方案:

    public static void sortedWords(String unsorted[]) throws IOException {
        sort(unsorted);
    
        try(PrintWriter out = new PrintWriter(new OutputStreamWriter(
                new FileOutputStream("sorted_words.txt"), "UTF-8"), true)) {
            Arrays.stream(unsorted).forEach(out::println);
        }
    
    }
    

    您可能必须将main方法的签名更改为:

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

    这样代码就可以编译了

  3. # 3 楼答案

    移除println内有sortedWords()的for循环。在调用main中的sortedWords之后,将以下内容添加到sorted_words.txt文件的输出中:

    java.nio.file.Files.write(Paths.path("sorted_words.txt"), Arrays.asList(words));