我目前有一个数组,其中包含从GUI发出的一组命令。我可以将命令列表打印到屏幕上,但是在将这些命令写入文本文件时遇到问题。我需要一些建议。这是打印到控制台的代码。
for (int i = 0; i < movementArray.length; i++)
{
System.out.println(movementArray[i]);
}
答案 0 :(得分:1)
首先使用StringBuilder创建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());
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();
}
}
}
答案 1 :(得分:0)