Android : 바이트 단위로 파일을 읽는 방법?
Android 애플리케이션에서 파일 콘텐츠를 바이트 단위로 가져 오려고합니다. SD 카드의 파일을 이제 바이트 단위로 선택하고 싶습니다. 나는 봤지만 그런 성공은 없었다. 도와주세요
다음은 확장자가있는 파일을 가져 오는 코드입니다. 이를 통해 파일을 얻고 스피너에 표시합니다. 파일 선택시 파일을 바이트 단위로 가져오고 싶습니다.
private List<String> getListOfFiles(String path) {
File files = new File(path);
FileFilter filter = new FileFilter() {
private final List<String> exts = Arrays.asList("jpeg", "jpg", "png", "bmp", "gif","mp3");
public boolean accept(File pathname) {
String ext;
String path = pathname.getPath();
ext = path.substring(path.lastIndexOf(".") + 1);
return exts.contains(ext);
}
};
final File [] filesFound = files.listFiles(filter);
List<String> list = new ArrayList<String>();
if (filesFound != null && filesFound.length > 0) {
for (File file : filesFound) {
list.add(file.getName());
}
}
return list;
}
여기에 간단합니다.
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
manifest.xml에 권한을 추가합니다.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
다음은 라이브러리가 필요하지 않고 효율적인 전체 파일을 읽도록 보장하는 솔루션입니다.
byte[] fullyReadFileToBytes(File f) throws IOException {
int size = (int) f.length();
byte bytes[] = new byte[size];
byte tmpBuff[] = new byte[size];
FileInputStream fis= new FileInputStream(f);;
try {
int read = fis.read(bytes, 0, size);
if (read < size) {
int remain = size - read;
while (remain > 0) {
read = fis.read(tmpBuff, 0, remain);
System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
remain -= read;
}
}
} catch (IOException e){
throw e;
} finally {
fis.close();
}
return bytes;
}
참고 : 파일 크기가 MAX_INT 바이트 미만이라고 가정하고 원하는 경우 처리를 추가 할 수 있습니다.
오늘날 가장 쉬운 해결책은 Apache common io를 사용하는 것입니다.
byte bytes[] = FileUtils.readFileToByteArray(photoFile)
유일한 단점은 build.gradle앱 에이 종속성을 추가하는 것입니다 .
implementation 'commons-io:commons-io:2.5'
+ 1562 메서드 카운트
허용되는 BufferedInputStream#read것이 버퍼 크기를 직접 추적하는 것이 아니라 모든 것을 읽는다는 보장이 없기 때문에 다음 접근 방식을 사용했습니다.
byte bytes[] = new byte[(int) file.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytes);
전체 읽기가 완료 될 때까지 차단되며 추가 가져 오기가 필요하지 않습니다.
이를 위해 openFileInputContext 의 메소드를 사용하려면 다음 코드를 사용할 수 있습니다.
그러면 BufferArrayOutputStream파일에서 읽을 때 각 바이트 가 생성 되고 추가됩니다.
/**
* <p>
* Creates a InputStream for a file using the specified Context
* and returns the Bytes read from the file.
* </p>
*
* @param context The context to use.
* @param file The file to read from.
* @return The array of bytes read from the file, or null if no file was found.
*/
public static byte[] read(Context context, String file) throws IOException {
byte[] ret = null;
if (context != null) {
try {
InputStream inputStream = context.openFileInput(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int nextByte = inputStream.read();
while (nextByte != -1) {
outputStream.write(nextByte);
nextByte = inputStream.read();
}
ret = outputStream.toByteArray();
} catch (FileNotFoundException ignored) { }
}
return ret;
}
다음과 같이 할 수도 있습니다.
byte[] getBytes (File file)
{
FileInputStream input = null;
if (file.exists()) try
{
input = new FileInputStream (file);
int len = (int) file.length();
byte[] data = new byte[len];
int count, total = 0;
while ((count = input.read (data, total, len - total)) > 0) total += count;
return data;
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (input != null) try
{
input.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
return null;
}
간단한 InputStream은
byte[] fileToBytes(File file){
byte[] bytes = new byte[0];
try(FileInputStream inputStream = new FileInputStream(file)) {
bytes = new byte[inputStream.available()];
//noinspection ResultOfMethodCallIgnored
inputStream.read(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
다음은 전체 파일을 청크로 읽는 작업 솔루션과 스캐너 클래스를 사용하여 큰 파일을 읽는 효율적인 솔루션입니다.
try {
FileInputStream fiStream = new FileInputStream(inputFile_name);
Scanner sc = null;
try {
sc = new Scanner(fiStream);
while (sc.hasNextLine()) {
String line = sc.nextLine();
byte[] buf = line.getBytes();
}
} finally {
if (fiStream != null) {
fiStream.close();
}
if (sc != null) {
sc.close();
}
}
}catch (Exception e){
Log.e(TAG, "Exception: " + e.toString());
}
참조 URL : https://stackoverflow.com/questions/10039672/android-how-to-read-file-in-bytes
'Program Club' 카테고리의 다른 글
| XML 레이아웃에서 "탭 순서"를 설정할 수 있습니까? (0) | 2021.01.05 |
|---|---|
| 배열이있는 배열을 문자열로 정렬 (0) | 2021.01.05 |
| 장치를 감지하는 방법은 Android 전화 또는 Android 태블릿입니까? (0) | 2021.01.05 |
| JavaScript는 다중 스레드입니까? (0) | 2021.01.05 |
| 이름이 변수에 포함 된 Perl 서브 루틴을 어떻게 우아하게 호출 할 수 있습니까? (0) | 2021.01.05 |