0

I'm starting with java, and now I'm doing some exercises on read/writing files.

I write strings with this format:

String wordList: word1 word2 word3; word4 word5 word6; code

Then I write this to the file using this code:

public void writeSelling(String wordList) throws IOException {

        fileOutPutStream = new FileOutputStream (file);
        write= new ObjectOutputStream (fileOutPutStream);
        write.writeObject(wordList);
        write.close();
        contador++;
    }

But where I'm not getting able to do it right is when reading it. For now, what I get is a null when reading the content of the file, so I think that I'm doing something wrong on the method.

This is the method I use to read the file:

public ArrayList<Object> readSelling() throws Exception, FileNotFoundException, IOException {

    ArrayList<Object> objectList = new ArrayList<Object>();
    fileInPutStream = new FileInputStream (file);
    read= new ObjectInputStream (fileInPutStream);
    for (int i=0; i<contador; i++){
        objectList.add(read.readObject());
    }
    read.close();
    return objectList;
}

I call this method this way on the main file:

public static void listSelling(){
    ArrayList objects;
    try{
        objects = sellingObject.readSelling();
        for (Iterator it = sellingObject.iterator(); it.hasNext();) {
            String s = (String)it.next();
            System.out.println(s.toString());
        }
    }catch(FileNotFoundException fnfe){
        System.out.println(fnfe.getMessage());
    }catch(IOException ioe){
        System.out.println(ioe.getMessage());
    }catch(Exception e){
        System.out.println(e.getMessage());
    }
}

I don't have knowledge enough to work with the Iterator, so maybe I'm not using it right.

UPDATE -- Definition of "file.dat

This file is defined this way in other class:

private final String file;

public WriteReadObject(String file){
    this.file= file;
}

Then in the main file is called this way:

static WriteReadObject selling= new WriteReadObject("file.dat");

UPDATE 2 --

I see that when I'm writing to the file, I'm writing a null value, and here is where it fails.

I have this:

String one = word1 word2 word3

String two = word4 word5 word6

Before call the write method to write on the file, I add these 2 strings in another string to get only one string. To do this I've created this method:

public String add(String c, String m){
    sellinglist[contador] = c + m;
    contador++;
    String list= sellinglist[contador];
    return list;
}

Where c is string one and m y string two

masmic
  • 3,526
  • 11
  • 52
  • 105
  • I think we are missing some crucial detail to be able to assist you here. Where is the declaration of the `file` variable, and is it ever assigned a value? – ninesided Nov 27 '13 at 12:21
  • Open your file and check whether the data has been written by your code in file or not. – AJ. Nov 27 '13 at 12:32
  • @ninesided I've updatede the post with the file definition – masmic Nov 27 '13 at 13:11
  • @masmic_87 swap lines `contador++;` and `String list= sellinglist[contador];` – Maciej Dobrowolski Nov 27 '13 at 14:33
  • @Maciej Dobrowolski excuse me but, what do you mean with swap? – masmic Nov 27 '13 at 14:40
  • 1
    @masmic_87 change position, make it: `sellinglist[contador] = c + m; String list= sellinglist[contador]; contador++; return list;` – Maciej Dobrowolski Nov 27 '13 at 14:41
  • Works this function now. I'll do a review to have a look if it works now – masmic Nov 27 '13 at 14:44
  • @Maciej Dobrowolski, even if I still use my code, to write only one string into the file, I don't achieve to do this. As you have told me in your answer below, I've done the "test.txt", but it doesn't generate any file. Do I have to manually create this file? If yes, where do I place it?? – masmic Nov 27 '13 at 15:16
  • @masmic_87 just make sure that you're looking for this file in the right directory. file should be generated automatically – Maciej Dobrowolski Nov 27 '13 at 15:26
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/42055/discussion-between-maciej-dobrowolski-and-masmic-87) – Maciej Dobrowolski Nov 27 '13 at 16:39

2 Answers2

1

The problem is you are writing single object and try to read an array of objects. Every time you are writing object you rewrite current file. Change openning of output stream to append data to file (but don't forget to clear it when writing first object):

fileOutPutStream = new FileOutputStream (file, contador != 0);
alexey28
  • 5,170
  • 1
  • 20
  • 25
  • How would I do this in my code? Sorry but as I said, I'm still learning about java – masmic Nov 27 '13 at 13:14
  • Edit my answer with based on contador counter logic – alexey28 Nov 27 '13 at 16:19
  • I think that I understand a bit what do you refer to, but, could you explain a litle bit what does exactly what you've posted? I must be able to call several times the method that writes the string into the file. Each time I call the method, it only writes one string, but this string can't override the actual string inside the file, so if I call 3 times the method, there should be 3 strings inside of it. – masmic Nov 28 '13 at 08:38
1

alexey28 said the right thing - you're rewriting the file and finally there's only the last insertion. Anyway it's not that simple to just change FileOutputStream argument to make it work - you can't just append to an ObjectOuputStream - if you would like to, see here. It will corrupt the stream what will result in StreamCorruptedException.

The best solution would be to open ObjectOutputStream once at the begining, write all objects you want and then close stream.


Update

It all depends on how you receive data which are to be written (If you are writing strings then it would be probably more comfortable to do it not in binary mode but text - here is tutorial which explains how to do that).

If you want code how to simply write list of Strings then you can try this:

/* writing */
public void writeSelling(List<String> wordLists) throws IOException {
    fileOutPutStream = new FileOutputStream (file);
    write= new ObjectOutputStream (fileOutPutStream);
    for (String s : wordLists) {
        write.writeObject(s);
    }
    write.close();
    contador++;
}

Now you can change code in the place where you call writeSelling().

/* calling method */
List<String> wordLists = new ArrayList<String>();
{ // it's probably loop
    String wordList = // somehow receive list like word1 word2 word3; word4 word5 word6; code
    wordLists.add(wordList);
}
writeSelling(wordLists);

The rest remains the same. Don't call writeSelling() method multiple times, just once.

Community
  • 1
  • 1
Maciej Dobrowolski
  • 11,561
  • 5
  • 45
  • 67
  • I'm starting with java and this is a bit above my knowledge, so, I would appreciate if you could edit with an example of how to do it using my code – masmic Nov 27 '13 at 13:15
  • @masmic_87 what about this? – Maciej Dobrowolski Nov 27 '13 at 13:30
  • I'm trying first with my code, and I'm seeing that when I write on the file, just 1 string, the I open manually the file and there isn't nothing written. So before adapting the code with your code, why could be this?? – masmic Nov 27 '13 at 14:17
  • @masmic_87 your `writeSelling()` method is correct and works. Try to replace `fileOutPutStream = new FileOutputStream (file);` line with `fileOutPutStream = new FileOutputStream ("test.txt");` (in `writeSelling()` method and run `main()` with just one line - `writeSelling("i'm sure it works");`. In result you should get a test.txt file with size more than 0kB :) – Maciej Dobrowolski Nov 27 '13 at 14:25
  • Thanks @Maciej Dobrowolski, but I found where is it doing wrong. Have a look if you can help me. I think is a easy thing, but I cannot find what I'm doing worng. I'm updating now the post – masmic Nov 27 '13 at 14:27
  • Ok! I generated manually but now writes, the problem is that first said, if I write one string does right, if i write the second returns null. So, I'm adapting your code, the las thing that I need to know, in you code you say `//it's probably` loop and seems like there is something missing there, can you explain me please what should I put there? – masmic Nov 27 '13 at 15:35
  • @masmic_87 I just don't know how you are getting these `wordList` variables. Probably it's in loop when you're asking user to input it many times, or reading a file line by line. The idea is to just gather all `wordLine` variables in a `List` and then pass it to the method. – Maciej Dobrowolski Nov 27 '13 at 16:39
  • The method you posted isn't working neither. The thing is that I must be able to call `writeSelling()` the times I need. For example, I create a string, and I write it on the file using the method. Then I can read the file, or create another string and save it on the file too, so, here will be 2 strings on the file that I save them into the file in diferent times. Now the method is done to write multiple strings at a time, but that is not what I need to do, what I need is to be able to call the method several times, and each time saces only one string inside the file – masmic Nov 28 '13 at 08:34