【问题标题】:Writing to a test file: Error within code?写入测试文件:代码中的错误?
【发布时间】: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里面创建文件吗?

标签: java file java-io


【解决方案1】:

我认为你应该使用File.getAbsolutePath() 在 UNIX 系统上,相对路径名通过根据当前用户目录解析而成为绝对路径名。在 Microsoft Windows 系统上,通过将相对路径名解析为由路径名命名的驱动器的当前目录(如果有),从而使相对路径名成为绝对路径;如果不是,则针对当前用户目录进行解析。

【讨论】:

    【解决方案2】:

    你当前的执行目录是:new File(".").getAbsolutePath(),检查那里

    【讨论】:

      猜你喜欢
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      相关资源
      最近更新 更多