So I have a file that has one line of int : 5551212
I am trying to use InputStream to read this file and then see if I can extract the number written within in it
I did the following steps:
import java.io.*;
class Shuffle {
public static void main(String args[]) throws IOException {
FileInputStream newfile = new FileInputStream("file path");
System.out.println(newfile.getChannel());
System.out.println(newfile.getFD());
System.out.println("Number of remaining bytes:"+newfile.available());
int data;
while ((data = newfile.read()) != -1) {
System.out.print(data + " ");
}
newfile.close();
}
}
However, the output that I got is: 53, 53, 53, 49, 50, 49, 50
I am not really sure what this is suppose to represent, or simply how do I use InputStream on integers
With Java 11 or above, a file can be read using a single line of code - Files.readString
Here is a working example for reading a text file:
// File name: ReadFile.java
import java.nio.file.*;
public class ReadFile {
public static void main(String[] args) throws Exception {
String path = "my-file.txt";
// Read file content as a string
System.out.println(Files.readString(Paths.get(path)));
}
}
Output:
> javac ReadFile.java
> java ReadFile
5551212