[英]How to replace the first line of a txt document
我想替换文档Vokabeln.txt的第一行,其中存储了词汇的数量,这样当添加一个词汇时,数量就会增加一个。 谢谢你帮助我。
import java.io.*;
public class Vokabeltrainer
{
private String file;
private String line;
private int anzahlVokabeln;
private boolean status = true;
Scanner sc = new Scanner(System.in);
private ArrayList <Vokabel> Vokabelliste;
public Vokabeltrainer()
{
this.file = "";
this.Vokabelliste = new ArrayList<Vokabel>();
}
public void main() throws IOException
{
System.out.println("Vokabeln.txt");
this.file = ("Vokabeln.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file)))
{
line = br.readLine();
anzahlVokabeln = Integer.parseInt(line);
for(int i = 0;i < anzahlVokabeln; i++)
{
line = br.readLine();
this.Vokabelliste.add(new Vokabel(line.split("\\s+")[0],line.split("\\s+")[1]));
}
}
while(status==true)
{
System.out.println("Was willst du machen \n-Vokabel hinzufügen\n-Vokabel enfernen\n-Vokabeln Abfragen\n-Programm Quit");
String line = sc.nextLine();
if(line.equals("one")||line.equals("Add vocabulary"))
{
Vokabelhinzufügen();
}
else if(line.equals("two")||line.equals("Remove vocabulary"))
{
}
else if(line.equals("three")||line.equals("Vokabeln Abfragen"))
{
}
else if(line.equals("four")||line.equals("Quit"))
{
status = false;
//Maybe Statistics from the User
}
else
{
System.out.println("This option doesnt exists.");
}
}
}
public void Vokabelhinzufügen()
{
boolean vokabelhinzustatus = true;
String Vokabel = "";
while(vokabelhinzustatus==true)
{
System.out.println("Please enter the vocabulary now. (Hallo Hello)");
Vokabel = sc.nextLine();
try(PrintWriter output = new PrintWriter(new FileWriter("Vokabeln.txt",true)))
{
output.printf("%s\r\n", Vokabel.toLowerCase());
String after = String.valueOf(anzahlVokabeln+1);
String before = String.valueOf(anzahlVokabeln);
//At this point the replace has to be. before is the number before the translation was added and after is after the translation was added.
}
catch (Exception e) {}
System.out.println("Vocabulary Successfully Added");
System.out.println("Exit Add Vocabulary?");
String line = sc.nextLine();
if(line.equals("yes"))
{
break;
}
}
}
public void Vokabelentfernen()
{
}
}
不是您的问题的答案; 一个设计建议。
看起来您有一个文件,其中存储了一些东西(可能是 Vokablin),并且文件中的每个东西的结构都相同,但包含不同的细节。
不要将计数存储在文件中。 相反,只需将内容存储在文件中并全部读取。
如果必须,请在文件末尾添加一个标记,指示“内容结束”。 出于某种原因,您可能希望在文件中存储一些事物。 如果是这种情况,请将计数存储为文件结束标记的一部分。
如果您使用此技术,您的添加到文件算法将变为:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.