Java 如何将行号添加到输入文件

Java 如何将行号添加到输入文件,java,file-io,string-formatting,Java,File Io,String Formatting,因此,我正在编写一个方法,它接收文件输入和文件输出。读取输入文件并将行号添加到行中,因此它应为“1 |行”,因此数字右对齐,3个空格后跟数字,一个“|”前后各有一个空格。我打印这行时遇到问题。到目前为止,我的代码是: public class LineNumbers { public static void process(File input, File output) { ArrayList<String> fileInput = new ArrayLis

因此,我正在编写一个方法,它接收文件输入和文件输出。读取输入文件并将行号添加到行中,因此它应为“1 |行”,因此数字右对齐,3个空格后跟数字,一个“|”前后各有一个空格。我打印这行时遇到问题。到目前为止,我的代码是:

public class LineNumbers {
    public static void process(File input, File output) {
        ArrayList<String> fileInput = new ArrayList<String>();
        ArrayList<String> out = new ArrayList<String>();
        int counter = 0;
        int counter1= 1;
        try {
            Scanner scanner = new Scanner(input);
            PrintWriter writer = new PrintWriter(output);
            while (scanner.hasNextLine()) {
                fileInput.add(scanner.nextLine());
                String a = fileInput.get(counter);
                String line = String.format("%3s | " ,counter1,a);
                out.add(line);
                counter++;
                counter1++;
                for(String n:fileInput){                    
                    writer.println(n);
                }

            }
            scanner.close();
            writer.close();
        } catch (IOException e) {
        }

    }
}
公共类行号{
公共静态作废过程(文件输入、文件输出){
ArrayList fileInput=新的ArrayList();
ArrayList out=新的ArrayList();
int计数器=0;
int计数器1=1;
试一试{
扫描仪=新扫描仪(输入);
PrintWriter=新的PrintWriter(输出);
while(scanner.hasNextLine()){
fileInput.add(scanner.nextLine());
字符串a=fileInput.get(计数器);
String line=String.format(“%3s |”,计数器1,a);
out.添加(行);
计数器++;
计数器1++;
对于(字符串n:fileInput){
println(n);
}
}
scanner.close();
writer.close();
}捕获(IOE异常){
}
}
}
您有:

String.format("%3s | " ,counter1,a);
您将
a
作为参数传递,但没有告诉
String.format()
如何处理它,因此它什么也不做

我没有看到与
a
对应的格式说明符。你很可能是说:

String.format("%3s | %s" ,counter1,a);

根据您的问题,为每行添加行号。以下代码适用于您

public static void process(File input, File output)
{
    try
    {
        Scanner scanner = new Scanner(input);
        PrintWriter writer = new PrintWriter(output);
        int counter = 1;
        while (scanner.hasNextLine())
        {
            String nextLine = scanner.nextLine();
            String line = String.format("%3s | %s", counter, nextLine);
            counter++;
            writer.println(line);
        }
        scanner.close();
        writer.close();
    }
    catch (IOException e)
    {
    }

}

在该行的正上方有字符串a=fileInput.get(计数器);你说的格式说明符是什么意思?@user3511198是的,我没有看到
a
的格式说明符“你说的格式说明符是什么意思?”我指的是“格式说明符”,与在中使用的方式相同。这适用于第一行,因此它可以工作,但是对于第二行和第二行,它不是迭代的number@user3511198那么听起来你有不止一个问题,但我们很难判断,因为你只说了“我打印这行有问题”,别的什么都没有。请编辑您的问题,以清楚地描述您的问题。喂食会使我们的网站整体变得更糟。