Java에서 파일로 바이트 []
Java의 경우:
나는 가지고 있다byte[]
파일을 나타냅니다.
파일에 쓰는 방법(즉, C:\myfile.pdf
)
InputStream에서 끝난 건 알지만, 잘 안 풀리네요.
Apache Commons IO 사용
FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
아니면, 당신이 스스로 일을 만들겠다고 고집한다면...
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(myByteArray);
//fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
라이브러리 없음:
try (FileOutputStream stream = new FileOutputStream(path)) {
stream.write(bytes);
}
Files.write(bytes, new File(path));
FileUtils.writeByteArrayToFile(new File(path), bytes);
이 모든 전략에서는 IOException도 어느 시점에서 파악해야 합니다.
다른 솔루션:java.nio.file
:
byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
또한 Java 7 이후 java.nio.file과 한 줄.파일:
Files.write(new File(filePath).toPath(), data);
여기서 data는 바이트[], filePath는 문자열입니다.StandardOpenOptions 클래스를 사용하여 여러 파일 열기 옵션을 추가할 수도 있습니다.슬로우를 추가하거나 트라이/캐치로 둘러쌉니다.
Java 7 이후로는 리소스 사용 문을 사용하여 리소스 누수를 방지하고 코드를 읽기 쉽게 만들 수 있습니다.자세한 내용은 이쪽입니다.
당신의 글을 쓰려면byteArray
다음 작업을 수행할 파일로 이동합니다.
try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
fos.write(byteArray);
} catch (IOException ioe) {
ioe.printStackTrace();
}
시험해 보다OutputStream
더 구체적으로 말하면FileOutputStream
기본 예:
String fileName = "file.test";
BufferedOutputStream bs = null;
try {
FileOutputStream fs = new FileOutputStream(new File(fileName));
bs = new BufferedOutputStream(fs);
bs.write(byte_array);
bs.close();
bs = null;
} catch (Exception e) {
e.printStackTrace()
}
if (bs != null) try { bs.close(); } catch (Exception e) {}
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
/////////////////////// 1 바이트 [///////////////////]
Path path = Paths.get(p);
byte[] data = null;
try {
data = Files.readAllBytes(path);
} catch (IOException ex) {
Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
}
////////////////// 2 바이트 []에서 파일 ///////////////////////////////////////.
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
Input Stream을 사용하면 완료됩니다.
이것은 String Builder를 사용하여 바이트 오프셋과 길이의 배열을 읽고 인쇄하는 프로그램입니다.
"여기에 코드를 입력하세요.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//*This is a program where we are reading and printing array of bytes offset and length using StringBuilder and Writing the array of bytes offset length to the new file*//
public class ReadandWriteAByte {
public void readandWriteBytesToFile(){
File file = new File("count.char"); //(abcdefghijk)
File bfile = new File("bytefile.txt");//(New File)
byte[] b;
FileInputStream fis = null;
FileOutputStream fos = null;
try{
fis = new FileInputStream (file);
fos = new FileOutputStream (bfile);
b = new byte [1024];
int i;
StringBuilder sb = new StringBuilder();
while ((i = fis.read(b))!=-1){
sb.append(new String(b,5,5));
fos.write(b, 2, 5);
}
System.out.println(sb.toString());
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fis != null);
fis.close(); //This helps to close the stream
}catch (IOException e){
e.printStackTrace();
}
}
}
public static void main (String args[]){
ReadandWriteAByte rb = new ReadandWriteAByte();
rb.readandWriteBytesToFile();
}
}
콘솔의 O/P : fghij
새 파일의 O/P: cdefg
선인장을 맛볼 수 있습니다.
new LengthOf(new TeeInput(array, new File("a.txt"))).value();
상세: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html
언급URL : https://stackoverflow.com/questions/4350084/byte-to-file-in-java
'programing' 카테고리의 다른 글
Vue JS의 확인란에 대한 적절한 양방향 바인딩 (0) | 2022.07.28 |
---|---|
반복자를 목록으로 변환 (0) | 2022.07.28 |
malloc을 사용할 때마다 경고가 뜨는 이유는 무엇입니까? (0) | 2022.07.28 |
다른 vuex 모듈에서 getter에 액세스하는 방법 (0) | 2022.07.28 |
Vuex 작업, vuex 모듈 및 사용자 지정 이름의 mapActions (0) | 2022.07.28 |