使用FileInputStream和FileOutputStream
读(读整个文本):
@Test public void testRead() { FileInputStream fileInputStream = null; try { File file = new File("a.txt"); fileInputStream = new FileInputStream(file); byte[] buffer = new byte[5]; int len; while ((len=fileInputStream.read(buffer))!=-1){ System.out.print(new String(buffer,0,len)); } } catch (IOException e) { e.printStackTrace(); } finally { try { if(fileInputStream!=null) fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } }写:
@Test public void testWrite(){ FileOutputStream fileOutputStream = null; try { File file = new File("b.txt"); fileOutputStream = new FileOutputStream(file); fileOutputStream.write("hello".getBytes()); fileOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileOutputStream!=null) fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }复制:
@Test public void copy(){ FileInputStream fileInputStream =null; FileOutputStream fileOutputStream =null; try { File file1 = new File("1.png"); File file2 = new File("2.png"); fileInputStream = new FileInputStream(file1); fileOutputStream = new FileOutputStream(file2); byte[] buffer = new byte[5]; int len; while ((len=fileInputStream.read(buffer))!=-1){ fileOutputStream.write(buffer,0,len); fileOutputStream.flush(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileInputStream!=null) fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { if(fileOutputStream!=null) fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } }