どのようにして変換しますjava.io.Fileにbyte[]?
どのようにして変換しますjava.io.Fileにbyte[]?
回答:
それはあなたにとって最良の意味に依存します。生産性については、車輪を再発明してApache Commonsを使用しないでください。ここIOUtils.toByteArray(InputStream input)ですね。
Fileを読むのに使用されますbyte[]か?Java6を使用しているため、NIOメソッドを使用できません:(
                    JDK 7から使用できますFiles.readAllBytes(Path)。
例:
import java.io.File;
import java.nio.file.Files;
File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());
              JDK 7以降-1つのライナー:
byte[] array = Files.readAllBytes(Paths.get("/path/to/file"));
外部依存関係は必要ありません。
import java.nio.file.Files;しimport java.nio.file.Paths;ていない場合は追加してください。
                    import java.io.RandomAccessFile;
RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
Java 8のドキュメント:http : //docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html
基本的には、メモリで読み取る必要があります。ファイルを開き、配列を割り当て、ファイルの内容を配列に読み込みます。
最も簡単な方法はこれに似たものです:
public byte[] read(File file) throws IOException, FileTooBigException {
    if (file.length() > MAX_FILE_SIZE) {
        throw new FileTooBigException(file);
    }
    ByteArrayOutputStream ous = null;
    InputStream ios = null;
    try {
        byte[] buffer = new byte[4096];
        ous = new ByteArrayOutputStream();
        ios = new FileInputStream(file);
        int read = 0;
        while ((read = ios.read(buffer)) != -1) {
            ous.write(buffer, 0, read);
        }
    }finally {
        try {
            if (ous != null)
                ous.close();
        } catch (IOException e) {
        }
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
        }
    }
    return ous.toByteArray();
}
これには、ファイルの内容の不必要なコピーがいくつかあります(実際には、データが3回コピーされます:ファイルからbuffer、bufferへByteArrayOutputStream、からByteArrayOutputStream、実際の結果の配列へ)。
また、特定のサイズまでのメモリのみのファイルを読み取ることを確認する必要もあります(これは通常、アプリケーションに依存します):-)。
またIOException、関数の外側を扱う必要があります。
別の方法はこれです:
public byte[] read(File file) throws IOException, FileTooBigException {
    if (file.length() > MAX_FILE_SIZE) {
        throw new FileTooBigException(file);
    }
    byte[] buffer = new byte[(int) file.length()];
    InputStream ios = null;
    try {
        ios = new FileInputStream(file);
        if (ios.read(buffer) == -1) {
            throw new IOException(
                    "EOF reached while trying to read the whole file");
        }
    } finally {
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
        }
    }
    return buffer;
}
これには不要なコピーはありません。
FileTooBigExceptionカスタムアプリケーションの例外です。MAX_FILE_SIZE定数は、アプリケーションパラメータです。
大きなファイルの場合は、ストリーム処理アルゴリズムを考えるか、メモリマッピングを使用する必要があります(を参照java.nio)。
誰かが言ったように、Apache Commons File Utilsはあなたが探しているものを持っているかもしれません
public static byte[] readFileToByteArray(File file) throws IOException
使用例(Program.java):
import org.apache.commons.io.FileUtils;
public class Program {
    public static void main(String[] args) throws IOException {
        File file = new File(args[0]);  // assume args[0] is the path to file
        byte[] data = FileUtils.readFileToByteArray(file);
        ...
    }
}
              NIO APIを使用してそれを行うこともできます。合計ファイルサイズ(バイト単位)がintに収まる限り、このコードでこれを行うことができます。
File f = new File("c:\\wscp.script");
FileInputStream fin = null;
FileChannel ch = null;
try {
    fin = new FileInputStream(f);
    ch = fin.getChannel();
    int size = (int) ch.size();
    MappedByteBuffer buf = ch.map(MapMode.READ_ONLY, 0, size);
    byte[] bytes = new byte[size];
    buf.get(bytes);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    try {
        if (fin != null) {
            fin.close();
        }
        if (ch != null) {
            ch.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
MappedByteBufferを使用しているため、非常に高速だと思います。
Java 8がなく、数行のコードの記述を避けるために大規模なライブラリを含めることは悪い考えであると私に同意する場合:
public static byte[] readBytes(InputStream inputStream) throws IOException {
    byte[] b = new byte[1024];
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    int c;
    while ((c = inputStream.read(b)) != -1) {
        os.write(b, 0, c);
    }
    return os.toByteArray();
}
呼び出し元は、ストリームを閉じる責任があります。
// Returns the contents of the file in a byte array.
    public static byte[] getBytesFromFile(File file) throws IOException {        
        // Get the size of the file
        long length = file.length();
        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            // File is too large
            throw new IOException("File is too large!");
        }
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        InputStream is = new FileInputStream(file);
        try {
            while (offset < bytes.length
                   && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            }
        } finally {
            is.close();
        }
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
        return bytes;
    }
              throw new IOException("File is too large!");ファイルが大きすぎる場合はどうすればよいですか?それについて何か例はありますか?
                    それを行う簡単な方法:
File fff = new File("/path/to/file");
FileInputStream fileInputStream = new FileInputStream(fff);
// int byteLength = fff.length(); 
// In android the result of file.length() is long
long byteLength = fff.length(); // byte count of the file-content
byte[] filecontent = new byte[(int) byteLength];
fileInputStream.read(filecontent, 0, (int) byteLength);
              ファイルからバイトを読み取る最も簡単な方法
import java.io.*;
class ReadBytesFromFile {
    public static void main(String args[]) throws Exception {
        // getBytes from anyWhere
        // I'm getting byte array from File
        File file = null;
        FileInputStream fileStream = new FileInputStream(file = new File("ByteArrayInputStreamClass.java"));
        // Instantiate array
        byte[] arr = new byte[(int) file.length()];
        // read All bytes of File stream
        fileStream.read(arr, 0, arr.length);
        for (int X : arr) {
            System.out.print((char) X);
        }
    }
}
              .*悪い習慣と見なされています。
                    Guavaには、提供するFiles.toByteArray()があります。これにはいくつかの利点があります。
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
File file = getYourFile();
Path path = file.toPath();
byte[] data = Files.readAllBytes(path);
              コミュニティウィキの回答と同じアプローチを使用しますが、よりクリーンですぐにコンパイルできます(AndroidなどでApache Commonsライブラリをインポートしたくない場合は、推奨されるアプローチ)。
public static byte[] getFileBytes(File file) throws IOException {
    ByteArrayOutputStream ous = null;
    InputStream ios = null;
    try {
        byte[] buffer = new byte[4096];
        ous = new ByteArrayOutputStream();
        ios = new FileInputStream(file);
        int read = 0;
        while ((read = ios.read(buffer)) != -1)
            ous.write(buffer, 0, read);
    } finally {
        try {
            if (ous != null)
                ous.close();
        } catch (IOException e) {
            // swallow, since not that important
        }
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
            // swallow, since not that important
        }
    }
    return ous.toByteArray();
}
              私はこれが最も簡単な方法であると信じています:
org.apache.commons.io.FileUtils.readFileToByteArray(file);
              事前に割り当てられたバイトバッファーにバイトを読み取る場合は、この回答が役立ちます。
あなたの最初の推測はおそらく使用することでしょうInputStream read(byte[])。ただし、この方法には、使用が不当に困難になる欠点があります。EOFに遭遇しなくても、配列が実際に完全に満たされる保証はありません。
代わりに、をご覧くださいDataInputStream readFully(byte[])。これは入力ストリームのラッパーであり、上記の問題はありません。さらに、このメソッドは、EOFが検出されるとスローされます。ずっといい。
次の方法はjava.io.Fileをbyte []に変換するだけでなく、多くの異なるJavaファイル読み取りメソッドをテストするときに、ファイルを読み取る最も速い方法であることがわかりましたを相互。
java.nio.file.Files.readAllBytes()
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class ReadFile_Files_ReadAllBytes {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);
    byte [] fileBytes = Files.readAllBytes(file.toPath());
    char singleChar;
    for(byte b : fileBytes) {
      singleChar = (char) b;
      System.out.print(singleChar);
    }
  }
}
              サードパーティのライブラリを使用せずに別のソリューションを追加しましょう。Scott(リンク)によって提案された例外処理パターンを再利用します。そして、醜い部分を別のメッセージに移動しました(FileUtilsクラスで非表示にします;))
public void someMethod() {
    final byte[] buffer = read(new File("test.txt"));
}
private byte[] read(final File file) {
    if (file.isDirectory())
        throw new RuntimeException("Unsupported operation, file "
                + file.getAbsolutePath() + " is a directory");
    if (file.length() > Integer.MAX_VALUE)
        throw new RuntimeException("Unsupported operation, file "
                + file.getAbsolutePath() + " is too big");
    Throwable pending = null;
    FileInputStream in = null;
    final byte buffer[] = new byte[(int) file.length()];
    try {
        in = new FileInputStream(file);
        in.read(buffer);
    } catch (Exception e) {
        pending = new RuntimeException("Exception occured on reading file "
                + file.getAbsolutePath(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                if (pending == null) {
                    pending = new RuntimeException(
                        "Exception occured on closing file" 
                             + file.getAbsolutePath(), e);
                }
            }
        }
        if (pending != null) {
            throw new RuntimeException(pending);
        }
    }
    return buffer;
}
              public static byte[] readBytes(InputStream inputStream) throws IOException {
    byte[] buffer = new byte[32 * 1024];
    int bufferSize = 0;
    for (;;) {
        int read = inputStream.read(buffer, bufferSize, buffer.length - bufferSize);
        if (read == -1) {
            return Arrays.copyOf(buffer, bufferSize);
        }
        bufferSize += read;
        if (bufferSize == buffer.length) {
            buffer = Arrays.copyOf(buffer, bufferSize * 2);
        }
    }
}
              ファイルからバイトを読み取る別の方法
Reader reader = null;
    try {
        reader = new FileReader(file);
        char buf[] = new char[8192];
        int len;
        StringBuilder s = new StringBuilder();
        while ((len = reader.read(buf)) >= 0) {
            s.append(buf, 0, len);
            byte[] byteArray = s.toString().getBytes();
        }
    } catch(FileNotFoundException ex) {
    } catch(IOException e) {
    }
    finally {
        if (reader != null) {
            reader.close();
        }
    }
              //The file that you wanna convert into byte[]
File file=new File("/storage/0CE2-EA3D/DCIM/Camera/VID_20190822_205931.mp4"); 
FileInputStream fileInputStream=new FileInputStream(file);
byte[] data=new byte[(int) file.length()];
BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
bufferedInputStream.read(data,0,data.length);
//Now the bytes of the file are contain in the "byte[] data"
              これを試して :
import sun.misc.IOUtils;
import java.io.IOException;
try {
    String path="";
    InputStream inputStream=new FileInputStream(path);
    byte[] data=IOUtils.readFully(inputStream,-1,false);
}
catch (IOException e) {
    System.out.println(e);
}