【发布时间】:2015-06-08 13:20:50
【问题描述】:
我有一个包含一些单词的 txt 文件,我想做的是一次读取这个文件一个单词(字符串),操作这个字符串,然后写另一个 txt 文件,但保留原始单词的位置。例如,如果我的输入是这样的:
Hello, this is a
test
我希望我的输出在 2 行中,就像输入一样。使用我的代码,我得到了这样的东西(如附加):
hello,
this
is
a
test
这是我这部分的代码:
Scanner sc2=null;
try{
sc2 = new Scanner (new File(fileInput));
}catch(FileNotFoundException fnfe)
{
System.out.println("File not found");
}
while(sc2.hasNextLine())
{
Scanner s2=new Scanner (sc2.nextLine());
while(s2.hasNext())
{
String word = s2.next();
//Here i manipulate the string, and the result is stored in the string "a"
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileOutput, true))))
{
out.println(a);
}catch (IOException e){}
}
}
(fileInput 和 fileOutput 的定义类似
String fileInput="path";
我认为我正在使用的 PrintWriter 只是对文件进行附加,但我试图用 FileWriter 和 OutputStreamWriter 替换这个 PrintWriter 但他们只写了最后一个字符串(他们用最新的字符串覆盖每个字符串,所以最后我得到了一个只有最后一个字符串的txt)。
我必须一次读取输入文件一个单词,因为我需要对其执行一些操作,然后我必须以与输入相同的方式写入输出。如果单词是数字并且我对它们的操作是简单的 +1,则输入/输出将如下所示: 输入:
5, 7, 8,
4, 2
输出:
6, 8, 9,
5, 3
而不是像新行中的每个单词一样追加。
【问题讨论】:
标签: java file file-read file-writing