Java代码将文件的读取至到StringList中,再将List内容转化成源文件

当前项目中遇到一个问题需要复现bug原因:原项目中将Linux系统某文件读取后重新还原,导致文件权限变更,无法执行。

所以我单写了产生bug原因的代码:

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.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.swing.filechooser.FileSystemView;

public class changrclocal {

	public static void main(String[] args) throws IOException {
		List lst = new LinkedList();
		BufferedReader reader = new BufferedReader(new FileReader(new File("/root/test.txt")));
		try {
			String line = null;
			while ((line = reader.readLine()) != null) {
				lst.add(line);
			}
		} finally {
			reader.close();
		}
		//控制台输出结果
//		for (String line : lst) {
//			System.out.println(line);
//		}
		System.out.println("read ok");
		File file = new File("/root/test.txt");
        FileWriter fw = null;
        BufferedWriter bw = null;
        Iterator iter = lst.iterator();
        try {
            fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            while(iter.hasNext()) {
                bw.write(iter.next());
                bw.newLine();
            }
            bw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
	}

}

 

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