Java 一个字符串一个字符串地读取 txt 文件并写入另一个保持单词位置的 txt
Java read txt file string by string and write another txt keeping the position of the words
我有一个包含一些单词的 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,则 input/output 将如下所示:
输入:
5, 7, 8,
4, 2
输出:
6, 8, 9,
5, 3
而不是像在新行中的每个单词追加。
边读边写:
try(PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(fileOutput)))) {
while(sc2.hasNextLine()) {
String line = sc2.nextLine();
Scanner s2 = new Scanner(line);
while(s2.hasNext()) {
// use the words in line
}
// write the line
out.println(line);
}
}
我有一个包含一些单词的 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,则 input/output 将如下所示: 输入:
5, 7, 8,
4, 2
输出:
6, 8, 9,
5, 3
而不是像在新行中的每个单词追加。
边读边写:
try(PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(fileOutput)))) {
while(sc2.hasNextLine()) {
String line = sc2.nextLine();
Scanner s2 = new Scanner(line);
while(s2.hasNext()) {
// use the words in line
}
// write the line
out.println(line);
}
}