1

I am trying to create an external file with one line of text in that file, and then print that line of text out in a Java program. I have tried; however, I am having trouble. My code is not throwing any errors, it is just not working properly.

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

public class App {

public static void main(String[] args) {

    String terminate = "X";
    String Question = "";
    System.out.println("I am the all-knowing Magic 8 Ball!");

    do {
        Scanner scnr = new Scanner(System.in);
        System.out.println("");
        System.out.println("Ask your question here or enter 'X' to exit:");
        Question = scnr.nextLine();
        continueGame(Question); 
    } while (terminate != Question);


        String testData[] = {"test1", "test2", "test3"};
        writeFile(testData, "data.txt");
        ArrayList<String> fileContents = readFile("data.txt");

        if (terminate.equalsIgnoreCase(Question)) {
        for (String contents : fileContents) {
            System.out.println(contents);
        }        
    }
   }

public static void continueGame(String Question) {

    char terminate = 'X';
    char condition = Question.charAt(0);

    if (condition == terminate) 
    {
        System.out.println("");
        System.out.println("Thanks for playing!");
        System.exit(0);
    }
    try 
    {
        Random rand = new Random();
        int choice;
        choice = 1 + rand.nextInt(20);
        responseOptions(choice, Question);
    }
    catch (Exception e)
    {
        System.out.println("Error: Invalid");
    }
}

public static void responseOptions(int choice, String answer)
{
    switch (choice)
    {
        case 1: answer = "Response: It is certain"; break;
        case 2: answer = "Response: It is decidely so"; break;
        case 3: answer = "Response: Without a doubt"; break;
        case 4: answer = "Response: Yes, definitely"; break;
        case 5: answer = "Response: You may rely on it"; break;
        case 6: answer = "Response: As I see it, yes"; break;
        case 7: answer = "Response: Most likely"; break;
        case 8: answer = "Response: Outlook good"; break;
        case 9: answer = "Response: Yes"; break;
        case 10: answer = "Response: Signs point to yes"; break;
        case 11: answer = "Response: Reply hazy, try again"; break;
        case 12: answer = "Response: Ask again later"; break;
        case 13: answer = "Response: Better not tell you now"; break;
        case 14: answer = "Response: Cannot predict now"; break;
        case 15: answer = "Response: Concentrate and ask again"; break;
        case 16: answer = "Response: Don't count on it"; break;
        case 17: answer = "Response: My reply is no"; break;
        case 18: answer = "Response: My sources say no"; break;
        case 19: answer = "Response: Outlook not so good"; break;
        case 20: answer = "Response: Very doubtful"; break;
    }
    System.out.println("");
    System.out.println(answer);
}

public static void writeFile(String arrayToWrite[], String filename) {

    try {
        PrintWriter wordWriter = new PrintWriter("filename.txt");
        for (String words : arrayToWrite) {
            wordWriter.println(words + "\n");
        }
    } catch (Exception e) {
        String msg = e.getMessage();
        System.out.print(msg);
    }   
}

public static ArrayList<String> readFile(String filename) {
    ArrayList<String> fileContents = new ArrayList();
    File myFile = new File(filename);

    try {
        Scanner scnr = new Scanner(myFile);
        String tempStr = "";
        while (scnr.hasNextLine()) {
            tempStr = scnr.nextLine();
            fileContents.add(tempStr);
        }
    } catch (Exception e) {
        String msg = e.getMessage();
        System.out.println(msg);
    }
    return fileContents;
}  
}
  • Did you try closing the `PrintWriter` after writing? – BackSlash Jan 17 '17 at 17:36
  • what do you mean by not working properly? file is not created, or `writeFile()` is not called? Tell us more. – jack jay Jan 17 '17 at 17:39
  • 2
    In what way is it not working properly? One thing I see is you're appending an extra `\n` with each word even though you're already using `println`. – 4castle Jan 17 '17 at 17:40
  • @jackjay it seems like the file is not created, because when I go into the program file, i do not see the file – coding_insanity Jan 17 '17 at 17:41
  • the problem with `PrintWriter` methods is that they dont throw any error. [see this](http://stackoverflow.com/questions/12431757/java-why-dont-the-printwriter-or-printstream-classes-throw-exception). – jack jay Jan 17 '17 at 17:45
  • i think if `PrintWriter` works fine you will be getting a file in your directory as `filename.txt`. check it – jack jay Jan 17 '17 at 17:48

1 Answers1

1

The problem with your code is that although you are getting filename in writeFile() but you not making file having name as filename instead you are making a file with filename.txt. While in your readFile() you are reading a file filename which is not created yet , but new file(filename) will create a empty file is file doesn't exists. And now you are reading an empty file. Put below code in your writeFile(),

try{  
     FileWriter fw=new FileWriter(filename);  
     for (String words : arrayToWrite) {
        fw.write(words + "\n");
     } 
     fw.close(); 

   }catch(Exception e){
     System.out.println(e);
} 

For extra note try not using PrintWriter or PrintStreamWriter as they don't through error which will cause you problem.

jack jay
  • 2,493
  • 1
  • 14
  • 27
  • For some reason, the file is still not showing up in my program folder – coding_insanity Jan 17 '17 at 18:09
  • the same code is working here @coding_insanity, hoping you have imported the required. Can you tell me what your `filename` variable holds? – jack jay Jan 17 '17 at 18:22
  • It worked now, I just had to refresh it basically. Thank you for your help, I really appreciate it, is my code to display what the file contains wrong, because that doesn't seem to work either – coding_insanity Jan 17 '17 at 18:26