如何使用 java 编辑文本文件中的特定行?



我正在编写一个程序,允许用户在文本文件中输入多达 9999 个帐户,但是我遇到的问题是它们可以按任何顺序放置,但我必须按顺序打印它们。这是我的代码

import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.text.*;
public class CreateBankFile {
public static int lines = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Path file = Paths.get("/root/sandbox/BankAccounts.txt");
String line = "";
int acctNum = 0;
String lastName;
double bal;
final int QUIT = 9999;
try
{
OutputStream output = new BufferedOutputStream(Files.newOutputStream(file));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
while(acctNum != QUIT)
{
System.out.print("Enter the acct num less than 9999: ");
acctNum = input.nextInt();
if(acctNum == QUIT)
{
continue;
}
System.out.print("Enter a last name: ");
lastName = input.next();
if(lastName.length() != 8)
{
if(lastName.length() > 8)
{
lastName = lastName.substring(0, 8);
}
else if(lastName.length() < 8)
{
int diff = 8 - lastName.length();
for(int i = 0; i < diff; i++)
{
lastName += " ";
}
}
}
System.out.print("Enter balance: ");
bal = input.nextDouble();
line = "ID#" + acctNum + "  " + lastName + "$" + bal;
writer.write(line);
writer.newLine();
lines++;
}
writer.close();
}
catch(IOException e)
{
System.out.println("Error");
}
}
}

我的问题是,我怎样才能得到它,以便当用户输入"55"时,它被打印到文本文件的第 55 行?

你可以做这样的事情:

1(创建一个类来存储你的行(acctNum,lastName..等(

2(在你的方法中,创建一个你创建的类的数组列表,对于给定的数字"n",你的方法会解析所有的行,如果acctNum小于"n",你会用这一行创建一个新的实例,并把它添加到你的数组列表中

3(您将使用acctNum对数组列表进行排序,然后打印其内容

也许FileChannels会为你工作:

RandomAccessFile writer = new RandomAccessFile(file, "rw");
FileChannel channel = writer.getChannel();
ByteBuffer buff = ByteBuffer.wrap("Test write".getBytes(StandardCharsets.UTF_8));
channel.write(buff,5);//5 is the distance in the file

网络上有很多很好的例子。

在您的问题中,我认为您将 acctNum 作为行号,并且您想在文件中的此行号处添加一行,以便您可以做这样的事情。

List<String> readLines = Files.readAllLines(path, StandardCharsets.UTF_8);
readLines.set(acctNum- 1, data);
Files.write(path, lines, StandardCharsets.UTF_8);

我假设您使用的是 Java 7 或更高版本,所以我做了acctNum-1因为在 Java 7 或更高版本中,行号以 1 开头,因此您可以更改为acctNum.
参考:列表集((和蔚来

最新更新