java_生成并打开本地html文件
Posted chenyf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java_生成并打开本地html文件相关的知识,希望对你有一定的参考价值。
//生成文件:
/**
* 读取本地文件,并写入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 = prop.getProperty( "csv_url" ).trim();
//根据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 });
}
}
以上是关于java_生成并打开本地html文件的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Java Swing 应用程序的默认浏览器中打开 HTML 文件?
PyQt5 PyQt5安装及配置,从文件夹读取图片并显示,模拟生成素描图像