如何读取将读取包含文本的文件。读取每一行并将其发送到输出文件,并在其前加上行号

时间:2019-04-10 20:16:50

标签: java

该程序不会创建文件

Scanner in = new Scanner(System.in);

System.out.print("Input file: ");
String Mary = in.next();
System.out.print("Output file: ");
String outMary = in.next();

File inFile = new File ("Mary.txt");
Scanner inputFile = new Scanner(inFile);
PrintWriter outFile = new PrintWriter("Mary2.txt");

while (inputFile.hasNext())
{
  String input = in.nextLine();
  outFile.println(input);
}

我想读取我创建的文件,然后将其内容复制到每个行前带有行号的文件中。

1 个答案:

答案 0 :(得分:1)

尝试此代码,这将创建新文件以供输出。请注意,如果文件在写入之前已经存在,则会删除文件

           File inFile = new File("Mary.txt");
            Scanner inputFile = new Scanner(inFile);

          try(BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Mary2.txt")))) {
              int i=0;
              while (inputFile.hasNext()) {
                  String input = inputFile.next();
                  bw.write(i+"\\ ");
                  i++;
              }
              bw.flush();
          }