-1

I am trying to read a text file into an array, modify the array, and then store it back into the text file for future use.

The array is just one column wide, so I would like each line of the text file to be stored in each array element.

I am doing this in the middle of a big program, so the related answers which I've found before don't seem to fit in.

Here is my code:

checkReadHeader = parts[0];

if (checkReadHeader.equals("LETSDOIT"))
{
    readMsg = parts[1];
    readj = 0;

    if(readMsg.equals(logging1)){

        //---------------------------------------
        // READ readlist1.txt AND STORE IT INTO STRING ARRAY readlist
        //---------------------------------------
        try
        {
            fIn = context.openFileInput("readList1.txt");
            isr = new InputStreamReader(fIn);
            while ((charRead = isr.read(inputBuffer)) > 0)
            {
                String readString = String.copyValueOf(inputBuffer, 0, charRead);
                if(!readString.equals("\n"))
                {
                    readList[readj][0] += readString;
                }
                else
                {
                    readj += 1;
                }         
                inputBuffer = new char[100];
            }
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
    }

    //---------------------------------------
    // MODIFY readlist
    //---------------------------------------

    readList[j][0] = testdate;

    //---------------------------------------
    // STORE readlist BACK INTO TEXT FILE readlist1.txt
    //---------------------------------------

    try
    {
        fOut = context.openFileOutput("readList1.txt", context.MODE_WORLD_READABLE);
        osw = new OutputStreamWriter(fOut);
        osw.write(readList.toString());
        osw.flush();
        osw.close();
    }
    catch (IOException ioe)
    {
        ioe.printStackTrace();
    }
}

My declaration of variables are all ok, as I am only coming across a run-time error now. Please advise me of any errors in my code - thanks in advance:-)

  • What is the runtime-error? – Fildor Jun 27 '16 at 10:10
  • Did you consider using [read**Line**](https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()) ? – Fildor Jun 27 '16 at 10:13
  • I am trying to create a messaging app which records read reports sent back from the recipient. The app currently crashes whenever a read report is received. In addition, the readlist1.txt file is not updated as intended, presumably because the reading and storing stage is not implemented. – Black Hedgehog Jun 27 '16 at 10:14
  • 1
    Look, I do not have a magic bowl in which I see your Stacktrace ;) Please add it. But as far as I can guess, your reading code is messed up. – Fildor Jun 27 '16 at 10:16
  • I tried using readLine and the solution on this page: http://stackoverflow.com/questions/16100175/store-text-file-content-line-by-line-into-array, but the "path/of/text" variable is showing an error when I try to input "readlist". Can you please advise how to use readLine by modifying my code now? – Black Hedgehog Jun 27 '16 at 10:19
  • where/how are you initializing `readList`? – Katharina Jun 27 '16 at 10:40
  • I am initialising it in the same class by: String[][] readList = {}; – Black Hedgehog Jun 27 '16 at 10:57

1 Answers1

1

First of all, it doesn't make sense to use an array as the internal data structure for your file. Because you don't know how many lines you will read beforehand. A List<String> is more sufficient with ArrayList or LinkedList as an implementation.

Second: Don't use a raw Reader but a BufferedReader. With this BufferedReader you can read the file line by line with the method readLine(). Similarly you can use PrintWriter to write line by line to a file.

Third: You should use explicit character encoding. Don't rely on the standard encoding, because the standard encoding can be different for different operating systems (e.g. Windows-ANSI aka Cp1252 for Windows and UTF-8 for Linux).

Fourth: Use the try-with-resources statement to open the input and output streams. So it is easier for you to be sure they are closed in every case.

I assume the return type of context.openFileInput("readList1.txt") is 'InputStream` and the character encoding is UTF-8:

List<String> readList = new ArrayList<String>();
// Read the file line by line into readList
try(
  BufferedReader reader = new BufferedReader(new InputStreamReader(
      context.openFileInput("readList1.txt"), "UTF-8"));
) {
  String line;
  while((line = reader.readLine()) != null) {
    readList.add(line);
  } 
} catch(IOException ioe) {
  ioe.printStackTrace();
}

// Modify readList
// ...

// Write readList line by line to the file
try(
  PrintWriter writer = new PrintWriter(new OutputStreamWriter(
    context.openFileOutput("readList1.txt", context.MODE_WORLD_READABLE), "UTF-8")));
) {
  for(String line: readList) {
    writer.println(line); 
  }
  writer.flush();
} catch (IOException ioe) {
  ioe.printStackTrace();
}
vanje
  • 10,180
  • 2
  • 31
  • 47
  • The line try( BufferedReader reader = new BufferedReader(new InputStreamReader( context.openFileInput("readList1.txt"), "UTF-8")); ) is showing up as an error, and I think it's because either or both the return type and character encoding is wrong. How can I check this? – Black Hedgehog Jun 27 '16 at 15:18
  • What Java version do you use? The try-with-resources statement is only available since Java 7. – vanje Jun 27 '16 at 15:22
  • I'm using version 8, but I'm not sure if your method will actually solve my problem. I currently have a list of names in an array. If I receive a 'read' report from one of these people, I would like to store the date I received the report in another array called 'readList,' which would show up beside the list of names. Hence, I would be able to see who has read my message and the date it was read. – Black Hedgehog Jun 27 '16 at 15:30
  • Hm, I tried it with Java 7 and it should work with 8 too, What is the error message? Did you imported all classes? A `ArrayList` is similar to an array. You can access the elements via index efficiently like in an array. So there is no real difference, it handles only the dynamic enlargement while adding new elements. It seems you should enhance your knowledge about the Java collections. Relying only on arrays makes your life harder than needed. – vanje Jun 27 '16 at 15:55
  • The error message is that try-with-resources requires API level 19, while my current min is 15. Yes - I couldn't agree more with what you said. I'm still very new to Java, but have a deadline to meet soon. If I ever get the chance, I will learn everything properly. But thanks for all your help and patience today - it's very much appreciated:-) – Black Hedgehog Jun 27 '16 at 17:39