读取一个文本文档,例如有1~10行,要求按10~1行的顺序输出.并保存予原文件.

import java.io.File;   
import java.io.FileNotFoundException;   
import java.io.FileReader;   
import java.io.FileWriter;   
import java.io.IOException;   
import java.io.Reader;   
import java.io.Writer;   
  
/**  
 *   
 * @author admin  
 */  
public class Main {   
  
    /** Creates a new instance of Main */  
    public Main() {   
    }   
  
    /**  
     * @param args  
     *            the command line arguments  
     * @throws IOException  
     */  
    public static void main(String[] args) throws IOException {   
        // TODO code application logic here   
        // 按文件大小来产生构建buffer   
        char[] buffer = new char[(int) new File("D:\\新建 文本文档.txt").length()];   
        Reader reader = null;   
        try {   
            reader = new FileReader("D:\\新建 文本文档.txt");   
  
            int offset;   
            while ((offset = reader.read(buffer)) > 0)   
                System.out.print(new String(buffer, 0, offset));   
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        } finally {   
            if (reader != null)   
                try {   
                    reader.close();   
                } catch (IOException e) {   
                }   
        }   
        // 将整个文件读入,然后构造成一个String   
        String s = new String(buffer);   
        // 将这个String按换行符拆分成String数组   
        String[] reverse = s.split("\r\n");   
        // 构造文件,原来那个文件   
        File file = new File("D:\\新建 文本文档.txt");   
        Writer writer = new FileWriter(file);   
        for (int i = reverse.length - 1; i >= 0; i--) {   
            // 反转写入   
            writer.write(reverse[i] + "\r\n");   
        }   
        writer.close();   
    }   
  
} 

 或者

import java.io.BufferedReader;   
import java.io.File;   
import java.io.FileReader;   
import java.util.ArrayList;   
  
public class TxtReverse {   
  
    /**  
     * @param args  
     */  
    public static void main(String[] args) throws Exception {   
        // TODO Auto-generated method stub   
        FileReader fr = new FileReader(new File("d://a.txt"));   
        BufferedReader br = new BufferedReader(fr);   
        ArrayList<String> al = new ArrayList<String>();   
        String line;   
        while ((line = br.readLine()) != null) {   
            al.add(line);   
        }   
  
        for (int i = al.size() - 1; i >= 0; i--) {   
            System.out.println(al.get(i));   
        }   
    }   
}  

 

你可能感兴趣的:(java)