概述
//生成文件:
/**
* 读取本地文件,并写入StringBuffer ,以csv文件为例
*builders = new StringBuilders("<html><head><script>......<body>");调用方法前写入页面的开始标签,方法结束后append页面的结束标签
*/
private static void csvToCache(File csv,StringBuilder builders,StringBuilder jsons){
try {
String encoding="GBK";
DataInputStream in=new DataInputStream(new FileInputStream(csv));
BufferedReader br = new BufferedReader(new InputStreamReader(in,encoding));
String line = "";
int index = 1;//定义序号
int row=1;
while ((line = br.readLine()) != null) //读取到的内容给line变量
{
//do something;
if(row==1) {//跳过第一行表头
row++;
continue;
}
String contents[] = line.trim().split(",");//此处csv文件中每行的数据是按逗号分隔的
for(int i=1;i<contents.length;i++) {
//添加到相应的StringBuilder里面,builders.append("contents[i]");若有需要可使用index设置标识
}
index++;
}
br.close();
} catch (Exception e) {
System.out.println("csvToCache is error !");
e.printStackTrace();
}
}
/**
*根据StringBuffer的内容生成本地文件
*/
public static void createFile(StringBuilder builders,String url) {
try{
File file = new File(url);
if(file.exists()) {//删除原来的旧文件
file.delete();
}
PrintStream printStream = new PrintStream(new FileOutputStream(file));
printStream.println(builders.toString());
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
---------------------------------------
//打开文件:
//第一种: Object获取项目中的properties
InputStream in = Object. class .getResourceAsStream( "/com/demo/conf.properties" );
//第二种: 直接获得本地配置文件properties
FileInputStream in = new FileInputStream("D:\work\demo\conf.properties");
//加载properties文件
Properties prop = new Properties();
prop.load(in);
//从配置文件中获取 页面的位置,此处url为网页的绝对路径并解决乱码,如:d:/demo/index.html
String url = new String(prop.getProperty( "csv_url" ).trim().getBytes("ISO-8859-1"),"gbk");
//根据url打开网页
private static void browse(String url) throws ClassNotFoundException, IllegalAccessException,
IllegalArgumentException, InterruptedException, InvocationTargetException, IOException,NoSuchMethodException {
String osName = System.getProperty("os.name", "");
if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
} else if (osName.startsWith("Mac OS")) {
Class fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });
openURL.invoke(null, new Object[] { url });
} else { // Unix or Linux
String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)
browser = browsers[count];
if (browser == null)
throw new NoSuchMethodException("Could not find web browser");
else
Runtime.getRuntime().exec(new String[] { browser, url });
}
}
转载于:https://www.cnblogs.com/chenyf/p/7810089.html
最后
以上就是务实曲奇为你收集整理的java_生成并打开本地html文件的全部内容,希望文章能够帮你解决java_生成并打开本地html文件所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复