----------------解决方案--------------------------------------------------------
把A中看成STRING类型,然后从最后一读取,再写入B中。不知道这样可以不?
----------------解决方案--------------------------------------------------------
好像有个方法是倒转String内容的,记不清了,去看看API文档吧
----------------解决方案--------------------------------------------------------
这是栈的强项.
----------------解决方案--------------------------------------------------------
先把文件里面所有的都读进来放到StringBuilder里面
然后reverse()一下就可以了
----------------解决方案--------------------------------------------------------
问题是我不知道怎么把一个文件的内容读到一个string中……要是这一步解决了,就没什么问题了。
----------------解决方案--------------------------------------------------------
终于把程序写出来了。但是感觉我的算法很糟糕,也没有领会5楼说的采用stringbuilder的方法。厚着脸皮把程序贴出来大家看看吧。欢迎指正。
[CODE]import java.io.*;
public class ReserveCopy {
public ReserveCopy() {
}
public static void main (String[] args)throws IOException {
//创建文件对象
File inputFile=new File("D:\\My Documents\\想飞之心.txt");
File outputFile=new File("D:\\My Documents\\target.txt");
//文件输入和输出流对象
FileReader in=new FileReader(inputFile);
FileWriter out=new FileWriter(outputFile);
String temp="";
String txtStr="";
BufferedReader br=new BufferedReader(in);
//将文件A中的内容读到txtStr中
while(br.readLine()!=null)
{
temp=br.readLine();
txtStr+=temp;
}
char c[]=txtStr.toCharArray();
int i=txtStr.length()-1;
//将A中的内容反序写入B中
while(i>=0)
{
out.write(c[i]);
i--;
}
in.close();
out.close();
}
}[/CODE]
----------------解决方案--------------------------------------------------------
你这段代码有问题!!
public class ReserveCopy {
public ReserveCopy() {
}
public static void main (String[] args)throws IOException {
//创建文件对象
File inputFile=new File("D:\\My Documents\\想飞之心.txt");
File outputFile=new File("D:\\My Documents\\target.txt");
//文件输入和输出流对象
FileReader in=new FileReader(inputFile);
FileWriter out=new FileWriter(outputFile);
String temp="";
String txtStr="";
BufferedReader br=new BufferedReader(in);
//将文件A中的内容读到txtStr中
while(br.readLine()!=null)//改成(temp=br.readLine()) {
temp=br.readLine();//去掉
txtStr+=temp;
}
char c[]=txtStr.toCharArray();
int i=txtStr.length()-1;
//将A中的内容反序写入B中
while(i>=0)
{
out.write(c[i]);
i--;
}
in.close();
out.close();
}
}
----------------解决方案--------------------------------------------------------
其实你没必要这么麻烦,将txtStr用这个函数reverse()就可以了!
----------------解决方案--------------------------------------------------------
刚查了查JDK
StringBuffer类确实有个类叫做reverse()
public StringBuffer reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.
Let n be the length of the old character sequence, the one contained in the string buffer just prior to execution of the reverse method. Then the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence.
Returns:a reference to this StringBuffer object.
----------------解决方案--------------------------------------------------------