如何编写Java文本文件

Wil*_*con 61 java file-io file

以下代码不生成文件(我无法在任何地方看到该文件).缺什么?

try {
    //create a temporary file
    String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
        Calendar.getInstance().getTime());
    File logFile=new File(timeLog);

    BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
    writer.write (string);

    //Close writer
    writer.close();
} catch(Exception e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 119

我认为你的期望和现实并不匹配(但他们什么时候会这样做;))

基本上,你认为文件写入的位置和文件实际写入的位置不相等(嗯,也许我应该写一个if语句;))

public class TestWriteFile {

    public static void main(String[] args) {
        BufferedWriter writer = null;
        try {
            //create a temporary file
            String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
            File logFile = new File(timeLog);

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());

            writer = new BufferedWriter(new FileWriter(logFile));
            writer.write("Hello world!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e) {
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意,您的示例将覆盖任何现有文件.如果要将文本附加到文件,则应执行以下操作:

writer = new BufferedWriter(new FileWriter(logFile, true));
Run Code Online (Sandbox Code Playgroud)


Men*_*usa 16

我想补充一下MadProgrammer的答案.

在多行写入的情况下,执行命令时

writer.write(string);
Run Code Online (Sandbox Code Playgroud)

可能会注意到,在编写的文件中,即使它们在调试过程中出现或者在终端上打印了相同的文本,也会在编写的文件中省略或跳过换行符,

System.out.println("\n");
Run Code Online (Sandbox Code Playgroud)

因此,整个文本作为一大块文本出现,在大多数情况下是不可取的.换行符可以依赖于平台,因此最好使用java系统属性获取此字符

String newline = System.getProperty("line.separator");
Run Code Online (Sandbox Code Playgroud)

然后使用换行变量而不是"\n".这将以您希望的方式获得输出.

  • writer.newLine()直接写一个行分隔符,取自System.getProperty("line.separator") (2认同)

小智 14

在java 7中现在可以做到

try(BufferedWriter w = ....)
{
  w.write(...);
}
catch(IOException)
{
}
Run Code Online (Sandbox Code Playgroud)

w.close将自动完成


小智 5

它不是创建文件,因为您实际上从未创建过该文件。你为它做了一个对象。创建实例不会创建文件。

File newFile = new File("directory", "fileName.txt");
Run Code Online (Sandbox Code Playgroud)

你可以这样做来制作一个文件:

newFile.createNewFile();
Run Code Online (Sandbox Code Playgroud)

你可以这样做来创建一个文件夹:

newFile.mkdir();
Run Code Online (Sandbox Code Playgroud)