Java - 复制到新的txt文件

时间:2014-06-29 15:24:34

标签: java text copy

这个程序创建的新test1.txt文件是完全空的,原始文件test.txt中填充了类似" 50 3 21 57 10 20",基本上整数与它们之间有空格。

import java.util.*;
import java.io.*;

class AddOneToInts 

{

   public static void main(String [] args) throws IOException
   {
       Scanner scan = new Scanner(new BufferedReader(new FileReader( "test.txt" )));
       BufferedWriter writer = new BufferedWriter(new FileWriter( "text1.txt" ));
       boolean cont = true;
       String temp;

       while (cont) {
         if (scan.hasNextInt()) {
            temp = (scan.nextInt()+1) + " ";
            writer.write(temp);
         } else break;
      }
   }
}

3 个答案:

答案 0 :(得分:1)

您必须关闭Java流以将其内容刷新到文件:

   Scanner scan = new Scanner(new BufferedReader(new FileReader( "test.txt" )));
   BufferedWriter writer = new BufferedWriter(new FileWriter( "text1.txt" ));
   boolean cont = true;
   String temp;

   while (cont) {
     if (scan.hasNextInt()) {
        temp = (scan.nextInt()+1) + " ";
        writer.write(temp);
     } else break;
  }
  writer.close(); // <<------------------------

答案 1 :(得分:1)

关闭流的最佳做法:

import java.util.*;
import java.io.*;

public class AddOneToInts 
{
   public static void main(String [] args) throws IOException
   {
       Scanner scan = null;
       BufferedWriter writer = null; 

       try
       {
           scan =  new Scanner(new BufferedReader(new FileReader( "test.txt" )));
           writer = new BufferedWriter(new FileWriter( "text1.txt" ));
           boolean cont = true;
           String temp;

           while (cont) 
           {
               if (scan.hasNextInt()) 
               {
                   temp = (scan.nextInt()+1) + " ";
                   writer.write(temp);
               } 
               else break;
           }
       }
       catch(IOException e)
       {
           e.printStackTrace();
       }
       finally
       {
           if(writer != null)
           {
                try
                {
                    writer.close();
                }
                catch(IOException e) {}
           }

           if(scan != null)
           {
                try
                {
                    scan.close();
                }
                catch(IOException e) {}
           }
       }
    }
}

虽然Apache Commons-IO有一个可以“静默关闭流”的功能,所以你不必在finally块中写第二个try-catch块。

答案 2 :(得分:1)

我已经看到问题已经被提问者回答了。只是为了以后对于类似流相关问题的任何人的利益,思想将尝试添加更多的清晰度。缺少的是有效的

writer.flush()

BufferedWriter(或任何缓冲的Writer)在其缓冲区已满时自动刷新。我猜正常大小约为8K。这就是为什么在这种情况下它不会自动刷新。

writer.close()执行缓冲区flush()。所以close()有效。

但是,对于进程退出时的本机流,它会自动执行close()。这里它不是原生的,而是更高级别的缓冲区。为了说明示例中是否进行了以下替换,

//OutputStreamWriter writer=new OutputStreamWriter(new FileOutputStream("text1.txt"));
OutputStream out=new FileOutputStream("text1.txt");

//writer.write(temp);
out.write(temp.getBytes());

它甚至不需要flush()或close()来使用此示例 - 尽管这是正确的做法。