This site requires JavaScript, please enable it in your browser!
Greenfoot back
ranacoder96
ranacoder96 wrote ...

2020/9/24

java.io.IOException Stream Closed

ranacoder96 ranacoder96

2020/9/24

#
I was trying to do basic input output using FileInputStream and FileOutputStream , but it threw this error Please dont tell me why i am not using Scanner class for input , i was just trying out FileInputStream class Ok So This is the code: You can ignore the ShipPlayer , because that is just a basic ship object i added for no purpose
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class MyWorld extends World
{
    int counter=0;
    public MyWorld()
    {   
         
        super(600, 400, 1);
        //Add out object that is of the class ShipPlayer
        ShipPlayer shipPlayerObject = new ShipPlayer();
        addObject(shipPlayerObject,300,200);
    }
     
    public void act(){
        if(counter<1){
            FileInputStream stdin = new FileInputStream(FileDescriptor.in);
            FileOutputStream stdout = new FileOutputStream(FileDescriptor.out);
             
            StringBuilder storeString = new StringBuilder();
             
            int character;
            System.out.println("Enter some text");
            try{
                while((character=stdin.read())>-1){
                    if(character=='\n'){
                        break;  
                    }
                    storeString.append(character);
                }
             
             
                //byte[] bytes = storeString.toString().getBytes();
                stdout.write(storeString.toString().getBytes());
                stdout.write('\n');
                stdout.flush();
                stdin.close();
                stdout.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}
danpost danpost

2020/9/24

#
You cannot "steal" the standard input stream (FileDescriptor.in) from greenfoot, which uses it for the Greenfoot class methods getKey, ask and isKeyDown. The same may be true for stdout. Use Greenfoot.ask for user keyboard input of character strings and System.out.print or println for output.
You need to login to post a reply.