[英]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.