首页 > 编程 > Java > 正文

java IO

2019-11-08 02:19:37
字体:
来源:转载
供稿:网友

1.字符流和字节流 文件一般用字符流操作,图片、影音一般用字节流操作。 OutStream/InputStream 字节输入输出流 Reader/Writer 字符输入输出流 //文件的复制 public static void getData(String path1,String path2) throws IOException{ //path1指要复制的目标地址,path2指要复制到的路径 File file1=new File(path1); if(!file1.exits()){ throw new FileNotFoundException(“文件不存在!”); } File file2=new File(path2); if(!file2.exits()){ file2.creatNewFile(); } //读取文件 BufferReader br=new BufferReader(new Reader(file1)); //BufferReader用于操作大文件,避免内存溢出造成的OOM异常 StringBuffer sb=new StringBuffer(); BufferedWriter bw=new BufferedWriter(new FileWriter(file2)); char[] c=new char[1024]; int readSize=0; while((readSize=br.read(c))!=-1){ sb.append(c); bw.write(c,0,readSize); } System.out.PRitln(sb.toString()); br.close(); bw.close(); }

//图片,影音的复制 public static void copyTo(String souce,String target) throws IOException{ File file1=new File(souce); String name=souce.substring(souce.lastIndexOf(“/”)); File file2=new File(target+name); if(!file2.exists()){ file2.createNewFile(); } InputStream is=new FileInputStream(file1); OutputStream os=new FileOutputStream(file2); byte[] b=new byte[1024]; int readSize=0; while((readSize=is.read(b))!=-1){ os.write(b,0, readSize); } os.close(); is.close(); }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表