黑马程序员_IO流(三)——InputStream,OutputStream

来源:互联网 发布:c语言用什么编译器好 编辑:程序博客网 时间:2024/05/17 00:59
IO流(三)——InputStream,OutputStream
-------android培训、java培训、期待与您交流! ----------
InputStream:字节输入流
OutputStream:字节输出流

import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class CopyImageDemo {public static final String PATH = "file/";public static void main(String[] args) {BufferedInputStream bis = null;BufferedOutputStream bos = null;try {bis = new BufferedInputStream(new FileInputStream(PATH+"read.jpg"));bos = new BufferedOutputStream(new FileOutputStream(PATH+"write.jpg"));byte[] byteArr = new byte[1024];int num = 0;while ((num = bis.read(byteArr)) != -1) {bos.write(byteArr);}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();} finally {try {if (bos != null)bos.close();} catch (IOException e) {// TODO Auto-generated catch blockthrow new RuntimeException("FileOutputStream资源关闭失败");}try {if (bis != null)bis.close();} catch (IOException e2) {// TODO: handle exceptionthrow new RuntimeException("FileInputStream资源关闭失败");}}}}

字节流转成字符流,并加上字符编码
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;public class InputOutputDemo {public static void main(String[] args) {String str = ReadData();writeFile(str);}public static String ReadData() {BufferedReader br = null;StringBuilder sb = new StringBuilder();try {br = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));String str = null;while ((str = br.readLine()) != null) {if ("over".equals(str))break;sb.append(str + "\n");}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blockthrow new RuntimeException("字符编码不存在");} catch (IOException e) {// TODO Auto-generated catch blockthrow new RuntimeException("数据读取错误");} finally {try {if (br != null)br.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return sb.toString();}public static void writeFile(String str) {BufferedWriter bw = null;try {bw = new BufferedWriter(new FileWriter("file/InputOutput.txt"));String[] strArr = str.split("\n");for(String strFor:strArr){bw.write(strFor);bw.newLine();}} catch (IOException e) {// TODO: handle exceptionthrow new RuntimeException("数据写入文件失败");}finally{try {if (bw != null)bw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}



0 0
原创粉丝点击