简体   繁体   中英

Output not printing to txt file Java

I am trying to create a program which prints out all the possible combinations of the letters "AUGC". The output would really print to a txt file and the result would be a txt file with something like this: "AAA AAG AAC AAU AGA" etc Here is the code I have so far:

import java.io.*;
import java.util.*;
import java.lang.*;

public class Permute {

    static String s = "ACGU";

    static void permute(int level, String prefix) {

        if (level == 0) {
            String fileName = "out.txt";
            PrintWriter outputStream = null;
            try {
                outputStream = new PrintWriter(fileName);
                outputStream.println(prefix);
                System.out.println(prefix);
                outputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return;
        }
        for (int i = 0; i < s.length(); i++) {
            permute(level - 1, prefix + s.charAt(i));
        }
     }

    public static void main(String[] args) {
        int k = 2;
        permute(k, "");
    }   

}

Currently the program is printing all the output to the console and only the last permutation to the txt file. I would like it to print all the information to both.

Any help would be greatly appreciated

You are closing OutputStream prematurely. Since you are using recursion, pass OutputStream as a parameter to permute method from main method. Initialize stream and close it in main method.

I maybe wrong on this one but do you not need to include a "\\n" as part of your outputStream.println(prefix);

so that is looks like outputStream.println(prefix + "\\n");

This will help as it seems to replacing the line with the newest details and not on a new line which is what you seem to be looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM