This is a read-only archive of the old Scratch 1.x Forums.
Try searching the current Scratch discussion forums.

#1 2011-11-30 19:19:02

poopo
Scratcher
Registered: 2009-09-20
Posts: 1000+

Java Help 2

Now I'm learning writing to streams. I'm able to make an error free program but it won't write the chars. here is my code:

Code:

import java.io.*;

public class IOHandling{
    public static void save() throws IOException{
        char[] data = {'h','e','l','l','o'};
        File game = new File("hi.txt");
        FileWriter iS = new FileWriter(game);
        iS.write(data);
    }
}

My output is a empty file named hi.txt
What am I doing wrong?


http://i45.tinypic.com/28rnqki.jpg

Offline

 

#2 2011-11-30 19:37:28

BoltBait
Scratcher
Registered: 2009-03-09
Posts: 1000+

Re: Java Help 2

I'm no Java expert, but I'll guess that you need to close the file to flush the IO buffer.

try:

:
iS.write(data);
game.close();
:

or something like that.


Animated sigs must be banned!
http://boltbait.com/j.pnghttp://boltbait.com/s.pnghttp://boltbait.com/d.pnghttp://boltbait.com/a.pnghttp://boltbait.com/p.png

Offline

 

#3 2011-11-30 20:39:34

MathWizz
Scratcher
Registered: 2009-08-31
Posts: 1000+

Re: Java Help 2

BoltBait is correct but the proper code is:

Code:

import java.io.*;

public class IOHandling{
    public static void save() throws IOException{
        char[] data = {'h','e','l','l','o'};
        File game = new File("hi.txt");
        FileWriter iS = new FileWriter(game);
        iS.write(data);
        iS.close();
    }
}

http://block.site90.net/scratch.mit/text.php?size=30&text=%20A%20signature!&color=333333

Offline

 

#4 2011-12-01 10:57:52

ZeroLuck
Scratcher
Registered: 2010-02-23
Posts: 500+

Re: Java Help 2

You have to close the FileWriter,
than it will work!

Code:

import java.io.*;

public class IOTest {

    public static void main(String[] args) throws IOException {
        FileWriter out = null;
        try {
            out = new FileWriter(new File("test.txt"));
            out.write("Hello World".toCharArray());
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

http://3.bp.blogspot.com/-oL2Atzp0Byw/T465vIQ36dI/AAAAAAAAADo/1vqL4PvhkM0/s1600/scratchdachwiki.png

Offline

 

#5 2011-12-01 11:11:49

poopo
Scratcher
Registered: 2009-09-20
Posts: 1000+

Re: Java Help 2

Thanks.  smile  You guys are all so helpful!


http://i45.tinypic.com/28rnqki.jpg

Offline

 

Board footer