1. 程式人生 > >Java文件流之字節流

Java文件流之字節流

void nal clas 更新 exception return inpu 建立 turn

InputStream 與OutputStream是字節流中的輸入流和輸出流。

public class FileStream {

    public static void main(String[] args) {
        FileStream fs = new FileStream();
        // String content =
        // fs.readFileWithInputStream("/home/rding/file/File1.txt");
        // System.out.println(content);

        fs.writeFileWithOutputStream(
"/home/rding/file/File3.txt", "Hello File3"); // fs.copyFile("/home/rding/file/File3.txt", // "/home/rding/file/File4.txt"); } public void copyFile(String srcPath, String descPath) { InputStream inStream = null; OutputStream outStream = null; try { inStream
= new FileInputStream(srcPath); outStream = new FileOutputStream(descPath); int size = inStream.available(); byte[] byteArr = new byte[size]; inStream.read(byteArr); outStream.write(byteArr); } catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); } } public void writeFileWithOutputStream(String filePath, String content) { OutputStream outStream = null; byte[] byteArr = content.getBytes(); try {
        //註意,outStream第一次建立後,就不會更新了,必須關閉再重新建立 outStream
= new FileOutputStream(filePath); // outStream = new FileOutputStream(new File(filePath));        // 如果傳入參數true,則接著原來文件後面繼續寫,而不是覆蓋源文件。 // outStream = new FileOutputStream(filePath, true); // outStream = new FileOutputStream(new File(filePath), true); outStream.write(byteArr); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (outStream != null) { try { outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } public String readFileWithInputStream(String filePath) { InputStream inStream = null; String result = ""; try { inStream = new FileInputStream(filePath); // inStream = new FileInputStream(new File(filePath)); int size = inStream.available(); byte[] byteArr = new byte[size]; inStream.read(byteArr); result = new String(byteArr); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } }

Java文件流之字節流