当前位置: 技术问答>java相关
怎样访问在.jar里的图片文件?
来源: 互联网 发布时间:2015-06-11
本文导语: 一般应用程序用到的图片、影响文件放在哪儿为好? | Read a text file from a jar [ReadFromJar.java] import java.applet.*; import java.io.*; public class ReadFromJar extends Applet{ public void init(){ rea...
一般应用程序用到的图片、影响文件放在哪儿为好?
|
Read a text file from a jar
[ReadFromJar.java]
import java.applet.*;
import java.io.*;
public class ReadFromJar extends Applet{
public void init(){
readTextFromJar("datafile1.txt");
readTextFromJar("test/datafile2.txt");
}
public void readTextFromJar(String s) {
String thisLine;
try {
InputStream is = getClass().getResourceAsStream(s);
BufferedReader br = new BufferedReader
(new InputStreamReader(is));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Create 2 datafiles.
datafile1.txt in the same directory as ReadfromJar.class and datafile2.txt in a subdirectory called test [datafile1.txt]
datafile1 line 1
datafile1 line 2
datafile1 line 3
datafile1 line 4
datafile1 line 5
[testdatafile2.txt]
datafile2 line 1
datafile2 line 2
datafile2 line 3
datafile2 line 4
datafile2 line 5
Create the jar with jar cf readjar.jar ReadFromJar.class datafile1.txt testdatafile2.txt
Try with the follwing HTML page
See java console for output
[ReadFromJar.java]
import java.applet.*;
import java.io.*;
public class ReadFromJar extends Applet{
public void init(){
readTextFromJar("datafile1.txt");
readTextFromJar("test/datafile2.txt");
}
public void readTextFromJar(String s) {
String thisLine;
try {
InputStream is = getClass().getResourceAsStream(s);
BufferedReader br = new BufferedReader
(new InputStreamReader(is));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Create 2 datafiles.
datafile1.txt in the same directory as ReadfromJar.class and datafile2.txt in a subdirectory called test [datafile1.txt]
datafile1 line 1
datafile1 line 2
datafile1 line 3
datafile1 line 4
datafile1 line 5
[testdatafile2.txt]
datafile2 line 1
datafile2 line 2
datafile2 line 3
datafile2 line 4
datafile2 line 5
Create the jar with jar cf readjar.jar ReadFromJar.class datafile1.txt testdatafile2.txt
Try with the follwing HTML page
See java console for output
|
用
JarInputStream jin=new JarInputStream(new FileInputStream(FileName));
while(true){
JarEntry je=jin.getNextJarEntry();
if (je.getName().equals(PhotoFileName)){
in=new LineNumberReader(new InputStreamReader(jin));
// 读图片
in.read()
。。。。。
}
}
JarInputStream jin=new JarInputStream(new FileInputStream(FileName));
while(true){
JarEntry je=jin.getNextJarEntry();
if (je.getName().equals(PhotoFileName)){
in=new LineNumberReader(new InputStreamReader(jin));
// 读图片
in.read()
。。。。。
}
}