åèæµåå符æµè¯»åæ件
程序员文章站
2022-06-09 21:26:16
...
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>