我正在尝试创建一个将文本附加到现有文档的java程序。这就是它让我的目标:
import java.util.*;
import java.io.*;
public class Main
{
public main(String args[])
{
System.out.print("Please enter a task: ");
Scanner taskInput = new Scanner(System.in);
String task = taskInput.next();
System.out.print(task);
PrintWriter writer = new PrintWriter("res\tasks.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
}
}
我有一些错误,不知道如何修复它们。我看了Bufferedwriter,但我不知道它是如何使用的,是的,我看了javadocs。 C ++并不是那么复杂。再一次,我想知道如何使程序将文本附加到现有文件。它应该足够有效地制作成应用程序。是否有任何好的资源来教授如何编写/追加/读取文件? javadoc不是为我做的。
答案 0 :(得分:1)
Java中的main()
方法必须具有以下签名
public static void main(String[] args)
如果没有如上所述声明方法,JVM将无法运行您的程序。而且,就像您关闭了PrintWriter
一样,您也需要关闭Scanner
。
我建议你在深入了解File I / O之前先了解Java的基础知识,因为这个API会抛出很多已经检查过的Exception
,而对于那些刚接触Java的人来说,这只会让人感到非常困惑。 try catch
或throws
正在做什么。
答案 1 :(得分:0)
试试这个,
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("tasks.txt", true)));
答案 2 :(得分:0)
以下内容应该有效:
public static void main(String[] args) {
try{
Formatter out = new Formatter("fileName.txt");
out.format("Write this to file");
out.close();
} catch (Exception e) {
System.out.println("An error occurred");
}
}
这是使用Formatter对象来创建文件(如果它尚不存在),然后您可以像使用任何print方法写入文件一样使用“format”方法。 try和catch是编译b / c的必要条件,Formatter类的构造函数抛出必须捕获的异常。除此之外,请确保键入: {/ 1}}在文件的开头。
顺便说一句,C ++并不比Java lol容易。欢呼声。