import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * File copy using byte array stream * 1, file ---> byte array * 2, byte array ---> file * @author pence * @date December 28, 2017 */ public class MyIO3 { public static void main(String[] args) throws IOException { // get content from file and save to byte array byte[] data = getBytesFromFile("C:/software/workspace/workspace/Test/src/test/a.txt"); System.out.println(new String(data,"gbk")); //write byte array contents to file toFileFromByteArray(data, "C:/software/workspace/workspace/Test/src/test/b.txt"); } /** * Read byte array content and output to file * @param src * @param destPah * @throws IOException */ public static void toFileFromByteArray(byte[] src, String destPath) throws IOException{ //1. Create source File dest = new File(destPath); //2. Select the stream InputStream is = new BufferedInputStream(new ByteArrayInputStream(src));//Byte array input stream OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));//File output stream //3. Operation byte[] flash = new byte[1024]; int len = 0; while(-1 != (len=is.read(flash))){ // output to file os.write(flash, 0, len); } os.flush(); //4. Close the stream os.close(); is.close(); } /** * Read file contents and output to byte array * @param srcPath * @return * @throws IOException */ public static byte[] getBytesFromFile(String srcPath) throws IOException{ //1. Create source File src = new File(srcPath); //source file byte[] dest = null; //destination array //2. Select the stream InputStream is = new BufferedInputStream(new FileInputStream(src)); //Buffered byte input stream ByteArrayOutputStream bos = new ByteArrayOutputStream(); //byte array output stream //3. Operation int len = 0; byte[] flash = new byte[1024]; while(-1 != (len=is.read(flash))){ // output to byte array bos.write(flash, 0, len); } bos.flush(); //retrieve data dest = bos.toByteArray(); //The new method is called here, so polymorphism cannot be used when creating objects //4. Close the stream bos.close(); is.close(); return dest; } }
IO stream operation three: use byte array stream to achieve file copy
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325444227&siteId=291194637
Ranking