0

I currently have an array that holds a set of commands issued from a GUI. I can print out the list of commands to the screen, but am having trouble writing those commands to a text file. I need some advice. This is the code that prints to the console.

for (int i = 0; i < movementArray.length; i++)
{
    System.out.println(movementArray[i]);
}
kenju
  • 5,866
  • 1
  • 41
  • 41
Hustl3r28
  • 211
  • 7
  • 16

2 Answers2

1

First use a StringBuilder to create your String:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < movementArray.length; i++)
{
    sb.append(movementArray[i]);
}
setContents(new File("your path here"), sb.toString());

The setContents(File aFile, String aContents) method will set a string content in a file.

public static void setContents(File aFile, String aContents)
            throws FileNotFoundException, IOException {
        if (aFile == null) {
            throw new IllegalArgumentException("File should not be null.");
        }
        if (!aFile.exists()) {
            throw new FileNotFoundException("File does not exist: " + aFile);
        }
        if (!aFile.isFile()) {
            throw new IllegalArgumentException("Should not be a directory: " + aFile);
        }
        if (!aFile.canWrite()) {
            throw new IllegalArgumentException("File cannot be written: " + aFile);
        }

        //declared here only to make visible to finally clause; generic reference
        Writer output = null;
        try {
            //use buffering
            //FileWriter always assumes default encoding is OK!
            output = new BufferedWriter(new FileWriter(aFile));
            output.write(aContents);
        } finally {
            //flush and close both "output" and its underlying FileWriter
            if (output != null) {
                output.close();
            }
        }
    }
elbuild
  • 4,869
  • 4
  • 24
  • 31