开启一个文本文件,并将该文档内字符以相反次序输出到另一个文档中

/*题目:编写一个Java程序要求:开启一个文本文件,
 *并将该文档内字符以相反次序输出到另一个文档中
 * */

package test;
import java.io.*;
import java.util.Scanner;

public class File_1_1
{
 /**
  * @param args
  */
 public void getFile(String pathreader,String pathwriter)
 {
  try
  {
   String st;  //字符串临时存储变量
   int i = 0;  //统计数组元素个数
   FileReader fr = new FileReader(pathreader);
   FileWriter fw = new FileWriter(pathwriter);
   BufferedReader br = new BufferedReader(fr);
   BufferedWriter bw = new BufferedWriter(fw);
   //返回文件内容的行数 countline(pathreader)
   String str[] = new String[countline(pathreader)];
   //利用StringBuffer对象主要是利用该对象中的倒序方法
   StringBuffer sub;
   StringBuffer data = new StringBuffer(br.readLine());
   while(data.toString() != null)
   {
    sub = new StringBuffer(data.toString().length());
    sub = data.reverse();  //将字符串的内容倒序
    str[i] = sub.toString();
 //   System.out.println(str[i]);
    i = i + 1;
    if((st = br.readLine()) != null)  //如果读取的文件不是null
     data = new StringBuffer(st);
    else  //否则退出循环
     break;
   }
   for(int j = str.length - 1; j >= 0; j--)
   {
    bw.write(str[j]);
    bw.newLine();
    bw.flush();
   }
   br.close();
   bw.close();
  }
  catch(IOException e)
  {
   System.out.println(e);
  }
 }
 
 //获取文件内容的行数
 public int countline(String pathreader)throws FileNotFoundException
 {
  int count = 0;
  File file = new File(pathreader); 
  FileInputStream fis = new FileInputStream(file); 
  Scanner scanner = new Scanner(fis); 
  while(scanner.hasNextLine())
  { 
   scanner.nextLine(); 
   count++; 
  }
  return count;
 }
 
 public static void main(String[] args)
 {
  // TODO 自动生成方法存根
  try
  {
   File_1_1 f1 = new File_1_1();
   f1.getFile("/java/java1.txt","/java/java2.txt");
  }
  catch(NullPointerException e)
  {
   System.out.println(e);
  }

 }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值