Java tutorial #1 Reading a file with FileInputStream
Firstly, we will have to create a main method, that throws an IOException in case of an error(File not found...)
public static void main(String[] args) throws IOException
Then, the actual InputStream object will have to be created.
InputStream f = new FileInputStream("steemit.txt");
Note: you will have to create a file "steemit.txt" in your java folder. In case you are using eclipse like me, it will look like this:
Now we are coming to the main part which looks like this
int content;
while((content = f.read()) != -1)
System.out.print((char)content);
It basically says that the file gets read and printed out as long as it's not the end of the file(-1). Now that the FileInputStream returns the byte and not the current character we are reading, we add a cast (char) so we can read it's output.
The final code looks like:
public class Filewrite4_3 {
public static void main(String[] args) throws IOException{
InputStream f = new FileInputStream("steemit.txt");
int content;
while((content = f.read()) != -1)
System.out.print((char)content);
}
}
And the output (In my case) is "Java Rocks!"
Stay tuned!