逐行读取文本文件,并在输出文件中将这些行插入到-d = sequence之后

时间:2015-05-30 07:25:37

标签: java text

I have an input file like below. An input file contains list of 8 digit numbers separated by comma. For that we need to read input file mentioned below.

12345678,
12345679,
12345680,
12345681,
12345682,
12345683,
12345684,
12345685    
as i have to read the above file. I need to insert first value after -d= sequence,second value at -d= sequence and so on...

finally output file must be:

D:\data\12345678.pdf -d=12345678 
D:\data\12345679.pdf -d=12345679 
D:\data\12345680.pdf -d=12345680 
D:\data\12345681.pdf -d=12345681 
D:\data\12345682.pdf -d=12345682 
D:\data\12345683.pdf -d=12345683 

此处路径和文件名不同。但主要目标是在每行的-d =序列之后插入这些值。

How can i achieve this?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

实现这一目标的一种方法是

package com.test.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.MessageFormat;

public class OutputGenerator {

    private static final String PATH = "D:\\data\\";
    private static final String FORMAT = PATH + "{0}.pdf -d={0}"; 

    public static void main(String[] args) throws IOException {
        String inputFile = "/Users/chatar/Documents/dev/projects/weekend-practice/stack-overflow/src/com/test/file/input.txt";
        String outputFile = "/Users/chatar/Documents/dev/projects/weekend-practice/stack-overflow/src/com/test/file/output.txt";

        FileReader reader = new FileReader(new File(inputFile));
        BufferedReader bufferedReader = new BufferedReader(reader);
        FileWriter writer = new FileWriter(outputFile);
        BufferedWriter bufferedWriter = new BufferedWriter(writer);


        try {
            while(bufferedReader.readLine() != null) {
                String inputLine = bufferedReader.readLine();
                System.out.println("inputline :: "+ inputLine);
                inputLine = inputLine.replaceAll("\\s+", "").replace(",", "");
                MessageFormat format = new MessageFormat(FORMAT);
                String outputLine = format.format(new Object[] {inputLine});
                bufferedWriter.write(outputLine);
                bufferedWriter.newLine();

            }  
        }
        finally {
            bufferedReader.close();
            bufferedWriter.close();
        }

    }
}