Java: read 与 write 文件

1 代码

//import java.io.IOException;
import java.io.*;

public class fileReadWrite{
     
    public static void main(String[] args) throws IOException{
     
       
        //paras: inputFile outputPath
        if(args.length < 2){
     
            printErr();
            System.exit(-1);
        }

        final String inputFile = args[0];
        final String outputPath = args[1];
        System.out.println("input-file: " + inputFile + "\noutput-path: " + outputPath);
        
        //file read & write function
        fileRW(inputFile, outputPath, " ");
    }

    //print paras error
    private static void printErr(){
     
        System.out.println("Paras: input-file output-path");
    }
    
    //read & write
    private static void fileRW(String inputFile, String outputPath, String delim) throws IOException{
     
        //read
        BufferedReader br = new BufferedReader(new FileReader(inputFile));

        //create path
        File dirPath = new File(outputPath);
        try{
     
            dirPath.mkdir();
        }catch(Exception e){
     
            System.out.println("Create " + outputPath +" error.");
        }

        //write
        BufferedWriter bw = new BufferedWriter(new FileWriter(outputPath + "/outputFile.txt"));
        
        System.out.println("output-file: " + outputPath + "outputFile.txt");
        bw.write("Begin to write >>> ");
        bw.newLine();

        while(true){
     
            final String line = br.readLine();
            if(line == null){
     
                break;
            }
            
            String[] buff = line.split(delim);
            int b0 = Integer.valueOf(buff[0]);
            int b1 = Integer.valueOf(buff[1]);
            int b2 = Integer.valueOf(buff[2]);
            
            System.out.println("First: " + b0 +", Second: " + b1 + ", Third: " + b2);
            
            bw.write(String.valueOf(b0));
            bw.write(delim);
            bw.write(String.valueOf(b1));
            bw.write(delim);
            bw.write(String.valueOf(b2));
            bw.newLine();
        }
        bw.close();
    }
}

2 结果

2.1 输入文件 inputFile.txt

Java: read 与 write 文件_第1张图片

2.2 控制台输出

Java: read 与 write 文件_第2张图片

2.3 输出文件 outputFile.txt

Java: read 与 write 文件_第3张图片

你可能感兴趣的:(Java,Linux)