【发布时间】: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");
}
}
}
【问题讨论】: