字节流跟字符流读取文件
字节流和字符流读取文件
jsp页面调用getTxt()
package io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.servlet.http.HttpServletRequest; public class ReadFile { public static void main(String[] args) { /** 读取字符流文件,并且把此文件复制到本地磁盘 */ String fromPath = "f://每日任务.txt"; String toPath = "f://1.txt"; ReadFile.readAndWriteTxt(fromPath, toPath); /** 读取字节流文件,并且把此文件复制到本地磁盘 */ // String fromPath = "f://3.gif"; // String toPath = "f://1.gif"; // ReadFile.readAndWriteImg(fromPath, toPath); } /** * FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。 * * @param fromPath * @param toPath */ public static void readAndWriteImg(String fromPath, String toPath) { File file = new File(fromPath); try { FileInputStream is = new FileInputStream(file); FileOutputStream os = new FileOutputStream(toPath); byte[] b = new byte[1024]; while (is.read(b) != -1) { os.write(b); } os.close(); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * FileReader 用于读取字符流。要读取原始字节流,请考虑使用 FileInputStream。 * * @param fromPath * @param toPath */ public static void readAndWriteTxt(String fromPath, String toPath) { File file = new File(fromPath); try { FileReader ir = new FileReader(file); BufferedReader br = new BufferedReader(ir); FileWriter ow = new FileWriter(toPath); BufferedWriter bw=new BufferedWriter(ow); char[] b = new char[1024]; while (ir.read(b) != -1) { ow.write(b); } ow.close(); ir.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 把文本内容输出到控制台和页面,这个是在jsp页面上调用的方法 */ public static String getTxt(HttpServletRequest request) { String fromPath = "f://每日任务.txt"; StringBuffer sb=new StringBuffer(); File file = new File(fromPath); try { FileReader ir = new FileReader(file); BufferedReader br = new BufferedReader(ir); String output; while((output=br.readLine())!=null){ sb.append(output+"\n"); System.out.println(output); } ir.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } }
jsp页面调用getTxt()
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="io.ReadFile"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <% String content = ReadFile.getTxt(request); %> </head> <body> <%=content %> </body> </html>