我有这样的方法:
public int getIncrement() {
String extractFolder = "/mnt/sdcard/MyFolder";
boolean newFolder = new File(extractFolder).mkdir();
int counter = 0;
try {
File root = new File(extractFolder);
if (root.canWrite()){
File gpxfile = new File(root, "gpxfile.txt");
FileWriter gpxwriter = new FileWriter(gpxfile);
BufferedWriter out = new BufferedWriter(gpxwriter);
Scanner scanner = new Scanner(new FileInputStream(gpxfile.getAbsolutePath()), "UTF-8");
Log.i("PATH: ", extractFolder + "/gpxfile.txt");
while(scanner.hasNextLine()) {
String inc = scanner.nextLine();
counter = Integer.parseInt(inc);
Log.i("INSIDE WHILE: ", Integer.toString(counter));
}
counter++;
out.write(Integer.toString(counter));
out.close();
}
} catch (IOException e) {
Log.e("GEN_PCN: ", "Could not write file " + e.getMessage());
}
return counter;
}
我想要完成的是返回此文件的内容,并将integer
增加1.但似乎我无法进入while
循环,因为{{1不打印任何东西。是的,我确定路径是正确的。
答案 0 :(得分:2)
我想FileWriter gpxwriter
的构造函数在创建Scanner
时已经消隐了文件,因此该文件为空,hasNextLine
返回false
。为什么要在阅读时打开文件进行写作?
答案 1 :(得分:1)
据我所知,该文件不存在。尝试添加gpxfile.createNewFile()
为了更深入一点,创建一个File实例,不会在文件系统上创建文件。
所以,这一行 - >文件gpxfile =新文件(路径,文件名);
不足以在SD卡上创建文件。你必须用
跟着它 引用docs的gpxfile.createNewFile()说:当且仅当具有此名称的文件尚不存在时,才会以原子方式创建一个由此抽象路径名命名的新空文件。检查文件是否存在以及文件的创建(如果不存在)是针对可能影响文件的所有其他文件系统活动的原子操作。
答案 2 :(得分:0)
确定我标记您的文件名
只需在摘要中的extractFolder 中添加 BACKSLASH
v
v
v
String extractFolder = "/mnt/sdcard/MyFolder/";
^ // <--- HERE
^
^
因为文件gpxfile =新文件(root,“gpxfile.txt”); 没有 BackSlash / ,因为日志有< / p>
试试以下:
while(scanner.hasNextLine()) {
String inc = scanner.nextLine();
// // counter = Integer.parseInt(inc);
Log.i("INSIDE WHILE: ", inc);
System.out.println("Next Line ::"+inc); // Also check this
}