I can use the scanner class to read binary files

2

I do not know if I can use it or not, can I use the Scanner class to read binary files?

    
asked by Alex Gómez 03.04.2017 в 11:06
source

2 answers

3

Class Scanner can not be used for binary files.

For this you can use for example FileInputStream .

    
answered by 03.04.2017 / 11:49
source
-1

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());

link

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);
            }
        }
    }
}

link

answered by 03.04.2017 в 12:40