无法从文本文件中读取行

时间:2012-08-01 14:03:51

标签: java android

我有这样的方法:

    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不打印任何东西。是的,我确定路径是正确的。

3 个答案:

答案 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
}
相关问题