Java 向文件追加数据
我试图读取文件,并在java程序读取的文本文件的每行开头打印一些文本。我试图这样做,但我打算打印的字符串被追加到文件末尾(在新行中)。但是,打印的次数与文本文件中的行数完全相同。这是代码Java 向文件追加数据,java,file-io,append,Java,File Io,Append,我试图读取文件,并在java程序读取的文本文件的每行开头打印一些文本。我试图这样做,但我打算打印的字符串被追加到文件末尾(在新行中)。但是,打印的次数与文本文件中的行数完全相同。这是代码 import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; i
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.io.BufferedReader;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.FileReader;
导入java.io.FileWriter;
导入java.io.IOException;
导入java.io.LineNumberReader;
导入java.util.Calendar;
导入java.util.Scanner;
导入java.util.TimeZone;
公共类字数{
公共静态void main(字符串[]args)引发IOException
{
尝试
{
文件=新文件(“文本文件位置”);
扫描仪输入=新扫描仪(新文件阅读器(“文本文件位置”);
int lc=0;
int-wc=0;
int l=0;
while(input.hasNextLine()){
String line=input.nextLine();
lc++;
字符串str[]=line.split((“”);
对于(int i=0;i 0)
{
wc++;
}
}
}
System.out.println(“行总数:“+lc”);
System.out.println(“总字数:“+wc”);
input.close();
//字符串名称=null;
//扫描仪k=新的扫描仪(System.in);
//name=k.next();
//int-wordcnt=wc;
//int l=0;
//对于(int j=0;j
资料来源:
如果你想在开始写,你必须把错误传递给构造函数,或者甚至不要传递第二个参数。记住这个附加的文件,它将替换文件中的内容。如果你想要写几行,在最上面的几行中,考虑一个字符串生成器,然后立刻写下所有的东西。p>
不能附加到文件的开头
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.