最近需要做一个小分享,打算讲一些手机上的技巧,为了在投影仪上显示,做了一个小应用,可以在电脑上实时显示手机界面,也可以模仿手机点击等操作,但是其中遇到了一个问题,因为最后需要导出jar形式文件,所以牵扯到jar文件读取问题,查询了一些资料,发现其实jar中文件读取也是非常的容易,写了个小例子,将一个文本中的内容读取,设置为标题。贴出来:
文件结构如下:
其中123.txt中的有2行内容,第一行是123,第二行是456,运行后界面:
代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* 读取jar文件中的资源文件
* @author Yuedong Li
*
*/
public class JarReadResource extends JFrame {
private static final long serialVersionUID = -6037197242318986298L;
public JarReadResource() {
StringBuffer title = new StringBuffer();
//获取jar中资源的输入流
InputStream is = this.getClass().getResourceAsStream("/doc/123.txt");
BufferedReader buff= new BufferedReader(new InputStreamReader(is));
try {
String line ;
while((line=buff.readLine())!=null){
title.append(line);
}
buff.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
this.setTitle(title.toString());
this.add(new JLabel("哈哈哈哈"),JLabel.CENTER);
this.setSize(200, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
new JarReadResource();
}
}原文:http://blog.csdn.net/dliyuedong/article/details/27711409