日期:2014-05-20  浏览次数:21064 次

将一个文件中的每一行内容反转 输出到另外一个文件

文件1中的内容
去我额人他一
去我而去我是

输出到另外一个文件
一他人额我去
是我去而我去

------解决方案--------------------
Java code

package csdn;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class ReverseRead {
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("test1.txt")));
            String str = "";
            while ((str = br.readLine()) != null) {                
                bw.write(Reverse(str) + "\n");
                bw.flush();
            }
            br = new BufferedReader(new InputStreamReader(new FileInputStream("test1.txt")));
            String s = "";
            while ((s = br.readLine()) != null) {
                System.out.println(s);
            }
            br.close();
            bw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }    
    }
    
    /**
     * 获得逆序的字符串
     * @param str 
     * @return str的逆序
     */
    private static String Reverse(String str) {
        char[] c = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = c.length - 1; i >= 0; i--) {
            sb.append(c[i] + "");
        }
        return sb.toString();
    }
}

------解决方案--------------------
1.读取文件1内容
2.将文件内容反转
3.将反转内容写入文件

假设文件一可以用字符流操作:

public static void reverse(String fileUrl) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(fileUrl)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}

BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileUrl+"_Copy")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}

String lineValue = "";
try {
while ((lineValue = br.readLine()) != null) {
int length = lineValue.length();
//char[] c = new char[length];
for (int i = length-1; i >=0 ; i--) {
//c[length -i -1] = lineValue.charAt(i);
bw.write(lineValue.charAt(i));
}
bw.write("\n");
//lineValue = new String(c);
}
} catch (IOException e) {
e.printStackTrace();
}

try {
br.close();
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}


功能差不多实现了。但可能有未知的BUG,没时间去看。楼主自己看看。