Writing contents of an array to a text file
本问题已经有最佳答案,请猛点这里访问。
我目前有一个数组,其中包含一组从GUI发出的命令。我可以将命令列表打印到屏幕上,但在将这些命令写入文本文件时遇到了困难。我需要一些建议。这是打印到控制台的代码。
1 2 3 4 |
首先使用StringBuilder创建字符串:
1 2 3 4 5 6 | StringBuilder sb = new StringBuilder(); for (int i = 0; i < movementArray.length; i++) { sb.append(movementArray[i]); } setContents(new File("your path here"), sb.toString()); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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(); } } } |
使用
http://docs.oracle.com/javase/7/docs/api/java/io/printwriter.html
http://docs.oracle.com/javase/7/docs/api/java/io/bufferedwriter.html