public class FileConverter {
private static Logger logger = Logger.getLogger(FileConverter.class);
/**
* url对象
*/
private URL url;
/**
* 输入流
*/
private BufferedReader in = null;
/**
* 输出流
*/
private BufferedWriter out= null;
/**
* url连接
*/
private URLConnection urlConn = null;
/**
* 文件对象
*/
private File file = null;
/**
* 输出文件夹对象
*/
private File folder = null;
/**
* 转换代码
* @param urlPath 转换源url地址
* @param savePath 转换后保存地址
* @param fileName 转换后文件名称
* @return 1成功 0失败 -1出现异常
*/
public int converter(String urlPath , String savePath , String fileName){
int state = 0;
try{
//创建url
url = new URL(urlPath);
//判断连接是否存在
if(!exists(url)){
return 0;
}
//创建http连接
urlConn = url.openConnection();
//创建输入流
in = new BufferedReader(new InputStreamReader(urlConn.getInputStream() , "utf-8"));
//创建文件夹对象
folder = new File(savePath);
//判断文件夹是否存在 , 不存在则创建文件夹
if(!folder.exists()){
folder.mkdirs();
}
//组合文件路径
String filePath = savePath+"//"+fileName;
//创建文件对象
file = new File(filePath);
//判断文件是否存在, 不存在则创建
if(!file.exists()){
file.createNewFile();
}
//创建输出流
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file) , "utf-8"));
//输出jsp文件头
out.write("<%@ page language=/"java/" pageEncoding=/"UTF-8/"%> /r/n");
int c = 0;
while((c=in.read())!=-1){
out.write(c);
}
state = 1;
}catch(Exception e){
state = -1;
e.printStackTrace();
}finally{
this.close();
}
return state;
}
/**
* 判断连接是否存在
* @param url
* @return
*/
private boolean exists(URL url){
try{
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
System.out.println(connection.getResponseCode());
if(connection.getResponseCode()==200){
return true;
}else{
return false;
}
}catch(Exception e){
e.printStackTrace();
}
return false;
}
/**
* 关闭流
*/
private void close(){
try{
if(this.in!=null){
this.in.close();
}
if(this.out!=null){
this.out.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String [] args){
FileConverter fc = new FileConverter();
fc.converter("http://www.earth-soft.com/dvd-tools/dvd-ripper.html", "D://", "a.jsp");
}
}
网页静态化
最新推荐文章于 2024-05-29 21:37:39 发布