【发布时间】:2014-02-27 12:37:46
【问题描述】:
以下代码中是否有错误,它似乎没有创建我想要的文本文件(numbers.txt)?我知道它应该在 JRE 系统库中创建文件,但我找不到它。
package test;
import java.io.FileNotFoundException;
import java.util.Formatter;
public class FileReaderTest {
private Formatter output;
/**
* default const
*/
public FileReaderTest() {
}
/**
* Method that enables a user to open a file
*/
public void openFile() {
try {
output = new Formatter("numbers.txt");
} catch (FileNotFoundException e) {
System.err.println("Problem found when opening file");
System.exit(1);// terminate
} catch (SecurityException Se) {
System.err.println("You dont have access to open file");
System.exit(1);// terminate
}
}// end of openFile
/**
* Method enabling user to write numbers to file
*/
public void writeToFile() {
// numbers to be written to file
Integer[] numbers = { 2, 5, 6, 7, 8, 9 };
for (Integer i : numbers) {
output.format("%d/n", i);
}
}// end of writeToFile
/**
* Method that closes file
*
*/
public void closeFile() {
if (output != null) {
output.close();
}
}// end of close file
}// class end
我在 Main 中的 fileReaderTest 实现:
public static void main(String[] args) {
//file input/putput testing
System.out.println("Opening file");
FileReaderTest file1= new FileReaderTest();
file1.openFile();//opening the file
file1.writeToFile();//writing values within the file
file1.closeFile();//closing the file
System.out.println("Finished with file");
}
}
【问题讨论】:
-
你有权限写应该写的地方吗?
-
它工作正常,它在该位置创建文件 - *Drive:\PathToProject\ProjectName*。
-
尝试将其写入绝对路径,例如: output = new Formatter("C:\\Users\\currentUser\\Desktop\\numbers.txt");
-
或使用 File 参数到 Formatter 并打印其 canonicalPath 以找出真实位置
-
不是在JRE库的eclipse里面创建文件吗?