Question

I'm trying to save a tokenized string into a .txt file... Example, in Read.txt is:

She sells, sea shells, by the sea shore.

I got my program to tokenize it but i can't seem to save the tokenized string into Write.txt

In Write.txt I just get:

She sells, sea shells, by the sea shore.

Basically I want to save what I output into Write.txt

Any help would be appreciated :D

Here are my outputs:

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.

And my current codes:

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!");
    }       
  }
}
Was it helpful?

Solution

You need to write() each token, append it with System.getProperty("line.separator"). A sample code will be :

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

Or, you can decorate your FileWriter with a PrintWriter and use its println() method for formatting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top