我想在文本文件中添加多个记录。所以我写了以下程序。但是在此程序中,每次用户从命令提示符输入数据时都会覆盖数据。在文件数据中覆盖。那么如何在文本文件中添加多个记录?
apples3.java
class apples3
{ public static void main(String[] args)
{ ffile g = new ffile();
g.get();
g.openFile();
g.addRecords();
g.closeFile();
}
}
ffile.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class ffile
{ private Formatter x;
Scanner sc = new Scanner(System.in);
int rollno;
String fname, lname;
public void get()
{ System.out.println("Enter rollno: ");
rollno = sc.nextInt();
System.out.println("Enter first name: ");
fname = sc.next();
System.out.println("Enter last name: ");
lname = sc.next();
}
public void openFile()
{ try
{ x = new Formatter("xyz.txt");
}
catch(Exception e)
{ System.out.println("You have an error");
}
}
public void addRecords()
{ x.format("%s %s %s ", rollno, fname, lname);
}
public void closeFile()
{ x.close();
}
}
添加记录后,我使用以下代码片段显示它:
Scanner x;
try
{ x = new Scanner(new File("Keyur.txt"));
while(x.hasNext())
{ String a = x.next();
String b = x.next();
String c = x.next();
String d = x.next();
System.out.printf("%s %s %s %s\n", a, b, c, d);
}
x.close();
}
catch(Exception e)
{ System.out.println("could not find file");
}
显示的输出如下cmd:
1 ghi mno
2 xyz abc
3 pqr def
其实我在java框架中运行这个程序。所以我拿了所有必要的文本框,标签,按钮。
当我在文本框中输入任何名称然后命名我要删除的特定行,例如我输入xyz然后从数据库txt文件中删除第2行xyz abc。登记/>
我在文本框和第二个文本框aaa中写pqr然后我想在我的txt文件中更新该记录。
所以,如果这可能,那么我只需要代码片段,那么它对我也很有用。
答案 0 :(得分:2)
尝试在append mode中打开信息流:
FileOutputStream fos = new FileOutputStream("xyz.txt", true);
x = new Formatter(fos);
答案 1 :(得分:2)
根据Java Doc,每次创建Formatter对象时,它都会覆盖该文件。您可以看到它here。试试这个:
import java.io.*;
import java.lang.*;
import java.util.*;
public class ffile
{
private File file;
BufferedWriter output;
private Formatter x;
Scanner sc = new Scanner(System.in);
int rollno;
String fname, lname;
public void get()
{ System.out.println("Enter rollno: ");
rollno = sc.nextInt();
System.out.println("Enter first name: ");
fname = sc.next();
System.out.println("Enter last name: ");
lname = sc.next();
}
public void openFile()
{ try
{
x = new Formatter();
file = new File("xyz.txt");
}
catch(Exception e)
{ System.out.println("You have an error");
}
}
public void addRecords()
{
try {
output = new BufferedWriter(new FileWriter(file,true));
output.write(x.format("%s %s %s \n", rollno, fname, lname).toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeFile()
{
x.close();
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 2 :(得分:1)
尝试使用此
public void openFile() {
try {
// APPEND MODE SET HERE
bw = new BufferedWriter(new FileWriter("xyz.txt", true));
x = new Formatter(bw);
} catch (Exception e) {
System.out.println("You have an error");
}
}
public void addRecords() {
x.format("%s %s %s", rollno, fname, lname);
x.format("%s", "\n");
}