2014-02-03 6 views
0

В настоящее время у меня есть массив, который содержит набор команд, выпущенных из графического интерфейса. Я могу распечатать список команд на экране, но у меня возникли проблемы с записью этих команд в текстовый файл. Мне нужен совет. Это код, который выводится на консоль.Запись содержимого массива в текстовый файл

for (int i = 0; i < movementArray.length; i++) 
{ 
    System.out.println(movementArray[i]); 
} 
+0

Хм, пожалуйста, попробуйте немного сложнее. java темы IO – Coffee

+1

Искать в Google или здесь: * «Написать в файл Java» *. – Christian

+0

Попробуйте googling 'java write array to file', десятки хороших примеров, некоторые из которых находятся на самой SO. – Durandal

ответ

1

Первое использование StringBuilder для создания строки:

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

Метод setContents(File aFile, String aContents) установит содержимое строки в файле.

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(); 
      } 
     } 
    } 
Смежные вопросы