0

Thanks everybody for the help. What I need to do is the following:

**Open a file for reading**

**Read the first token [String] in the file**

**Report the next Read_Cursor_Position**

**Return the token**

**Close the file**

**Reopen the file**

**Read the *second* token from the file**

and so on and so forth until all the necessary data has been read. I am new to Java, but in C++ tellg or tellp is used to extract the cursor position and getline for reading just the one token from a file. I hope this explanation better explain my question.

After writing a method that outputs data with a delimiter to a UTF file, I am now trying to extract the data from the UTF file. The way the data has to be extracted is one token at the time, the tokens, as I said before, have a delimiter and all Java has to do is read the file's token until the delimiter is found. Here is the code for the writer method:

public void writeData(String data) throws IOException {
    try {
        dout.writeUTF(data);
        dout.writeBytes("^");
    } catch(IOException e) {
        throw e;
    }
}

and here is the reader:

public void readData() throws IllegalStateException {
    try {
        apstr = new StringBuilder();
        while(scan.hasNext()) {
            apstr.delete(0,apstr.length());
            apstr.append(scan.next());
            System.out.println("The token is: " + apstr);
        }
    } catch(IllegalStateException e) {
        scan.close();
        throw e;
    }
    scan.close();
}

The file contains the following data: Java^C++^PHP^ and the output is: Java^C++^PHP^ but all I want to read is the word Java

How can I make Java do the same thing?

by the way, how do I go about posting a new question? There is no button on this web page that says "Post a new question". Thanks in advance.

Amno
  • 1
  • 4
  • so the Scanner is reading from the file? Then you don't want to use writeUTF. writeUTF doesn't encode the way you think it does. Use a Writer and specify UTF-8 encoding – MeBigFatGuy Feb 16 '17 at 21:36
  • 1
    Btw, you _cannot_ possibly be posting your exact code. The printline does not match your alleged output. :) – Keith Feb 16 '17 at 21:40

2 Answers2

0

You should write to your file using a Writer. If you want to use utf-8 encoding do something like

PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("somepath"), StandardCharsets.UTF_8)));

then do

pw.println("some text");

using DataOutputStream for stuff that you will be reading with a scanner isn't going to work.

MeBigFatGuy
  • 28,272
  • 7
  • 61
  • 66
-1

Use the StringTokenizer.

It contains a constructor StringTokenizer(String str, String delim) -- in which your delimiter will be the carat ("^") character, and a nextToken() function to return the next token as a String.

Also, this StackOverflow post demonstrates various options to reading your file into a String.

Community
  • 1
  • 1
Keith
  • 3,079
  • 2
  • 17
  • 26