我正在尝试将标记化字符串保存到.txt文件中...
示例,在Read.txt
中是:
She sells, sea shells, by the sea shore.
我让我的程序对其进行标记,但我似乎无法将标记化的字符串保存到Write.txt
在Write.txt
我得到:
She sells, sea shells, by the sea shore.
基本上我想将输出保存到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!");
}
}
}
答案 0 :(得分:2)
您需要write()
每个令牌,并附加System.getProperty("line.separator")
。示例代码为:
while( stnz2.hasMoreTokens()){
fw.write(stnz2.nextToken()+System.getProperty("line.separator"));
}
或者,您可decorate使用FileWriter PrintWriter并使用println()方法进行格式化。