I do not know if I can use it or not, can I use the Scanner class to read binary files?
I do not know if I can use it or not, can I use the Scanner class to read binary files?
Class Scanner
can not be used for binary files.
For this you can use for example FileInputStream
.
Some alternatives:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
Path path = Paths.get("path/to/file");
byte[] data = Files.readAllBytes(path);
byte[] array = Files.readAllBytes(new File("/path/to/file").toPath());
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReadFileInByteArrayWithFileInputStream {
public static void main(String[] args) {
File file = new File("inputfile.txt");
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
String s = new String(fileContent);
System.out.println("File content: " + s);
}
catch (FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch (IOException ioe) {
System.out.println("Exception while reading file " + ioe);
}
finally {
try {
if (fin != null) {
fin.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
}
}