我正在尝试读取文件并在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");
}
}
}
答案 0 :(得分:0)
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传递给构造函数,或者甚至不传递第二个参数。请记住,这不会附加到文件,它将替换文件中的内容。如果你想要的是写几行,最新的行在顶部,考虑一个字符串构建器,然后一次写入所有内容。
您无法追加到文件的开头。