【问题标题】:Appending data to a file将数据附加到文件
【发布时间】:2014-07-27 19:38:57
【问题描述】:

我正在尝试读取文件并在 java 程序读取的文本文件的每一行的开头打印一些文本。我试图这样做,但我打算打印的字符串被附加在文件的末尾(在新行中)。但是,它的打印次数与文本文件中的行数完全相同。这是代码。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Calendar;
import java.util.Scanner;
import java.util.TimeZone;


public class wordcount {

        public static void main(String[] args) throws IOException
        {
            try
            {
             File file =new File("Text file location");

              Scanner input = new Scanner(new FileReader("Text file location"));

               int lc = 0;
               int wc = 0;
                int l = 0;
                while (input.hasNextLine()) {

                   String line = input.nextLine();


                   lc++;

         String str [] = line.split((" "));
          for ( int i = 0; i <str.length ; i ++)
          {
            if (str [i].length() > 0)
            {
                wc ++;
            }
          }

        }
        System.out.println("Total number of lines :" +lc);
        System.out.println("Total number of words :" +wc);
        input.close();
//      String name = null;
//      Scanner k = new Scanner(System.in);
//      name = k.next();
//      int wordcnt = wc;
//      int l = 0;
//      for(int j=0 ; j<lc ; j++)
//      {

            while(l!=(wc))
            {
                wc--;
//  continue;
            }
            FileWriter writer = new FileWriter(file, true);
            writer.write("Hi" + System.getProperty("line_separator"));
                        writer.flush();
                            writer.close();
//  }
        }
        catch (FileNotFoundException e)
        {
        System.out.println("Error");
        }
        }
}

【问题讨论】:

    标签: java file-io append


    【解决方案1】:
    FileWriter writer = new FileWriter(file, true);
    
    public FileWriter(String fileName,
              boolean append)
               throws IOException
    Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
    Parameters:
    fileName - String The system-dependent filename.
    append - boolean if true, then data will be written to the end of the file rather than the beginning.
    

    来源:http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html

    如果你想在开头写你必须将 false 传递给构造函数,或者甚至不传递第二个参数。请记住,这不会附加到文件中,它将替换文件中的内容。如果您想要写几行,最近的行在顶部,请考虑使用字符串生成器,然后一次编写所有内容。

    您不能追加到文件的开头。

    【讨论】:

      猜你喜欢
      • 2022-08-14
      • 2021-07-21
      • 2014-09-25
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 2012-04-15
      相关资源
      最近更新 更多