Vinh La Kiến

51 bundles
1 file8 months ago
1

Java Read/Write file using InputStream/OutputStream

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
package com.company; import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class Main { private static byte[] ReadFile(String filePath) throws FileNotFoundException { File file = new File(filePath); System.out.println((int) file.length() / 1024 / 1024); try (InputStream in = new FileInputStream(file)) { byte[] bytes = new byte[(int) file.length()]; in.read(bytes); return bytes; } catch (Exception e) { e.printStackTrace(); } return null; } private static void foo() throws FileNotFoundException { byte[] fileData = ReadFile("E:\\Drive\\STDIO Gallery\\Larige\\IMG_0274.MOV"); while(true){} // Charset charset = StandardCharsets.UTF_8; // String content = new String(fileData, charset); // System.out.print(content); } public static void main(String[] args) throws FileNotFoundException { File file = new File("D:/filename.txt"); byte[] data = new byte[8]; for (int i = 0; i < data.length; i++) { data[i] = (byte)(i + 65); } data[5] = (byte)(13); data[6] = (byte)(10); data[7] = (byte)(97); try { file.createNewFile(); OutputStream out = new FileOutputStream(file); out.write(data); } catch (IOException e) { e.printStackTrace(); } System.out.println("OK"); } }