当前位置: 代码迷 >> 综合 >> JAVA中的I/O流实例
  详细解决方案

JAVA中的I/O流实例

热度:21   发布时间:2024-01-26 16:03:28.0

一、读文件 

public static void main(String args[]) throws Exception{File contentFile = null;FileInputStream fis = null;InputStreamReader isr = null;try {contentFile = new File("src/cn/duoduo/ddd.txt");if(contentFile.exists()) {fis = new FileInputStream(contentFile);StringBuffer sb = new StringBuffer(8192);isr = new InputStreamReader(fis, "utf-8");char buff[] = new char[4096];int length;while ((length = isr.read(buff, 0, 4096)) != -1) {if (length > 0) {sb.append(buff, 0, length);}}System.out.println(sb.toString());}} catch(FileNotFoundException e){e.printStackTrace();}finally {isr.close() ;fis.close() ;}}

二、复制文件

public static void main(String args[]) throws java.io.FileNotFoundException,IOException {try(FileInputStream input = new FileInputStream("src/cn/duoduo/ddd.txt");FileOutputStream output = new FileOutputStream("src/cn/duoduo/bbb.txt");BufferedInputStream bfInput = new BufferedInputStream(input);BufferedOutputStream bfOutput = new BufferedOutputStream(output);) {int r, bytesNumber = 0;while ((r = bfInput.read()) != -1) {bfOutput.write(r);bytesNumber++;}System.out.println("Destination.java有"+bytesNumber+"个字节");}}