IT이야기

Java에서 파일 to 바이트[]

cyworld 2022. 5. 10. 22:25
반응형

Java에서 파일 to 바이트[]

변환 convert 방법java.io.File완전히byte[]?

JDK 7에서 를 사용할 수 있다.

예:

import java.io.File;
import java.nio.file.Files;

File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());

그것은 당신에게 가장 좋은 의미가 무엇인지에 달려 있다.생산성이 현명하니, 바퀴를 재발명하지 말고 아파치 커먼스를 이용하십시오.그것은 여기에 있다.

JDK 7 이후부터 하나의 라이너:

byte[] array = Files.readAllBytes(Paths.get("/path/to/file"));

외부 의존성이 필요하지 않다.

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

이것은 파일 내용의 불필요한 복사를 한다(실제로 데이터는 파일로부터 파일로 세 번 복사된다).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);
        ...
    }
}

만약 당신이 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();
}

발신자는 스트림을 닫을 책임이 있다.

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를 사용해서 매우 빠른 것 같아.

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

간단한 방법:

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()를 가지고 있다.다음과 같은 몇 가지 장점이 있다.

  1. 파일 길이가 0인 경우 보고되지만 콘텐츠가 있는 경우
  2. OutOfMemory를 통해 고도로 최적화되었으며파일을 로드하기 전에 큰 파일에서 읽으려고 할 경우 예외(file.length()를 교묘하게 사용하여)
  3. 너는 바퀴를 다시 발명할 필요가 없다.
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);

커뮤니티 wiki가 대답하는 것과 동일한 접근 방식을 사용하되, 즉시 정리 및 컴파일(Apache Commons libs, 예를 들어 Android에서 수입을 원하지 않을 경우 선호되는 접근 방식):

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

Readually 현재 파일 포인터에서 시작하여 이 파일의 b.length 바이트를 바이트 배열로 읽으십시오.이 방법은 요청된 바이트 수가 읽힐 때까지 파일에서 반복적으로 읽는다.이 방법은 요청된 바이트 수를 읽거나 스트림의 끝을 감지하거나 예외를 발생시킬 때까지 차단한다.

RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);

이것은 가장 간단한 방법 중 하나이다.

 String pathFile = "/path/to/file";
 byte[] bytes = Files.readAllBytes(Paths.get(pathFile ));

바이트를 미리 할당된 바이트 버퍼로 읽으려면 이 대답이 도움이 될 수 있다.

당신의 첫 번째 추측은 아마도 사용하는 것일 것이다.그러나 이 방법에는 불합리하게 사용하기 어려운 결함이 있다. EOF가 발생하지 않더라도 배열이 실제로 완전히 채워질 것이라는 보장이 없다.

대신 을 보십시오.이것은 입력 스트림의 포장지로서, 위에서 언급한 문제가 없다.또한 이 방법은 EOF가 발생할 때 발생한다.훨씬 더 착하다.

다음 방법만이 java.io을 변환할 수 있는 것은 아니다.파일 형식[, 파일 형식] 또한 여러 Java 파일 읽기 방법을 서로 테스트할 때 파일에서 가장 빠르게 읽을 수 있는 방법임을 알게 되었다.

java.nio.file.파일.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);
    }
  }
}

타사 라이브러리를 사용하지 않고 다른 솔루션을 추가하십시오.스콧(링크)이 제안했던 예외 처리 패턴을 다시 활용한다.그리고 못생긴 부분을 별도의 메시지로 옮겼다(일부 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);
        }
    }
}
//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"

파일에서 바이트를 읽는 다른 방법

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

다음을 시도해 보십시오.

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

이것만큼 간단하게 할 수 있다(Kotlin 버전)

val byteArray = File(path).inputStream().readBytes()

편집:

의 문서를 읽은 적이 있다.readBytes방법다음과 같이 적혀 있다.

이 스트림을 바이트 배열로 완전히 읽는다.참고: 이 스트림을 닫는 것은 발신자의 책임이다.

모든 것을 깨끗하게 유지하면서 스트림을 닫으려면 다음 코드를 사용하십시오.

val byteArray = File(path).inputStream().use { it.readBytes() }

이 점을 지적해 준 @user2768856 덕분이다.

대상 버전이 26 API 미만인 경우 시도하십시오.

 private static byte[] readFileToBytes(String filePath) {

    File file = new File(filePath);
    byte[] bytes = new byte[(int) file.length()];

    // funny, if can use Java 7, please uses Files.readAllBytes(path)
    try(FileInputStream fis = new FileInputStream(file)){
        fis.read(bytes);
        return bytes;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;

}

JDK8인

Stream<String> lines = Files.lines(path);
String data = lines.collect(Collectors.joining("\n"));
lines.close();

참조URL: https://stackoverflow.com/questions/858980/file-to-byte-in-java

반응형