这是我的代码:
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class Append
{
public static void main( String[] args )
{
try{
String data = " Thank you very much";
File file =new File(" ");
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
System.out.println("New File Created Now");
}
//true = append file
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
}
}
在上面的代码中我试图添加" String data ="非常感谢你&#34 ;; "在G://Openone.txt,但它没有正确,我没有得到输出。
答案 0 :(得分:2)
public static void main( String[] args )
{
try{
String data = " Thank you very much";
File file =new File(" ");
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
System.out.println("New File Created Now");
}
//true = append file
FileWriter fileWritter = new FileWriter(file,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
fileWritter.close();
System.out.println("Done");
}catch(Exception e){
e.printStackTrace();
}
}
在以下行中使用文件对象而不是file.getName()
。
FileWriter fileWritter = new FileWriter(file.getName(),true);
答案 1 :(得分:1)
File file =new File(" ");
应该成为
File file = new File("G:\\Openone.txt");
答案 2 :(得分:1)
如果您使用的是Java 7+,则可以使用:
Files.write(Paths.get("G:\\Openone.txt"), "Thank you very much".getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
顺便说一下,我建议你重构代码,以便使用finally块正确管理异常,因为如果在写行中抛出异常,则不会调用close方法。