gpt4 book ai didi

java - 将标记化字符串写入文本文件?

转载 作者:行者123 更新时间:2023-11-30 04:17:51 25 4
gpt4 key购买 nike

我正在尝试将标记化字符串保存到 .txt 文件中...例如,在 Read.txt 中是:

她在海边卖贝壳。

我的程序对其进行了标记,但我似乎无法将标记化的字符串保存到 Write.txt

Write.txt 中我得到:

她在海边卖贝壳。

基本上我想将输出保存到Write.txt

任何帮助将不胜感激:D

这是我的输出:

She sells, sea shells, by the sea shore.

[Split by spaces.]

She
sells,
sea shells,
by
the
sea
shore.

-----------------------------

[Split by commas.]

She sells
sea shells
by the sea shore.

以及我当前的代码:

import java.io.*;
import java.util.StringTokenizer;


public class readWriteTokenized{
public static void main( String[] args ){

String readString;

try{
BufferedReader br = new BufferedReader( new FileReader("Read.txt"));

readString = br.readLine();
System.out.println("\n" + readString);

br.close();


StringTokenizer stnz = new StringTokenizer(readString);

System.out.println("\n[Split by spaces.]\n");
while( stnz .hasMoreTokens()){
System.out.println(stnz .nextToken());
}


StringTokenizer stnz2 = new StringTokenizer(readString, ".");

System.out.println("\n-----------------------------");
System.out.println("\n\n[Split by comma.]\n");
while( stnz2.hasMoreTokens()){
System.out.print(stnz2.nextToken());
}


File NewTextFile = new File("C:/TestJava/Write.txt");

FileWriter fw = new FileWriter(NewTextFile);
fw.write(readString);
fw.close();
}
catch (IOException e){
System.out.println("Catch error!");
}
}
}

最佳答案

您需要write()每个标记,并在其后面附加System.getProperty("line.separator")。示例代码如下:

while( stnz2.hasMoreTokens()){
fw.write(stnz2.nextToken()+System.getProperty("line.separator"));
}

或者,您可以decorate你的FileWriterPrintWriter并使用其 println()格式化方法。

关于java - 将标记化字符串写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17910908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com