[英]How to Write text file Java
以下代码不生成文件(我无法在任何地方看到该文件)。 缺什么?
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();
}
我认为你的期望和现实并不匹配(但他们什么时候有过);)
基本上,你认为文件写入的位置和文件实际写入的位置不相等(嗯,也许我应该写一个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) {
}
}
}
}
另请注意,您的示例将覆盖任何现有文件。 如果要将文本附加到文件,则应执行以下操作:
writer = new BufferedWriter(new FileWriter(logFile, true));
我想补充一下MadProgrammer的答案。
在多行写入的情况下,执行命令时
writer.write(string);
可能会注意到,在编写的文件中,即使它们在调试过程中出现或者在终端上打印了相同的文本,也会在编写的文件中省略或跳过换行符,
System.out.println("\n");
因此,整个文本作为一大块文本出现,在大多数情况下是不可取的。 换行符可以依赖于平台,因此最好使用java系统属性获取此字符
String newline = System.getProperty("line.separator");
然后使用换行变量而不是“\\ n”。 这将以您希望的方式获得输出。
在java 7中现在可以做到
try(BufferedWriter w = ....)
{
w.write(...);
}
catch(IOException)
{
}
w.close将自动完成
它不是创建文件,因为您从未真正创建过该文件。 你为它做了一个对象。 创建实例不会创建该文件。
File newFile = new File("directory", "fileName.txt");
你可以这样做一个文件:
newFile.createNewFile();
你可以这样做一个文件夹:
newFile.mkdir();
您可以尝试Java库。 FileUtils ,它有许多写入文件的函数。
它确实与我合作。 确保在timeLog旁边添加“.txt”。 我在一个用Netbeans打开的简单程序中使用它,它将程序写入主文件夹(builder和src文件夹所在的位置)。
使用java 8 LocalDateTime
和java 7 try-with语句:
public class WriteFile {
public static void main(String[] args) {
String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now());
File logFile = new File(timeLog);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile)))
{
System.out.println("File was written to: " + logFile.getCanonicalPath());
bw.write("Hello world!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.