在 Java 中,我尝试了在 jar 中读取文件的不同技术。我已经让一个在另一个程序中工作,但不是这个。我从 classname.class.getClassLoader().getResourceAsStream(filenamestring); 得到的 InputStream 方法返回 null。
package mainpkg;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class MainClass extends JFrame{
JTextField jtf = new JTextField();
boolean isInstalling = false;
public MainClass(){
super("StringThatTitleWillBe");
}
public void initiate(){
setLookAndFeel();
setSize(550, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout bl = new GridLayout(2, 1, 10, 10);
setLayout(bl);
JButton b = new JButton("Install");
b.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent arg0) {
if(!isInstalling){
isInstalling = true;
install();
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
});
add(b);
jtf.setEditable(false);
add(jtf);
//show
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exc) {
System.out.print("failed to load look and feel");
}
}
public static void main(String[] args){
MainClass m = new MainClass();
m.initiate();
}
public void install() {
String files = "name of jarfile inside the jar to be read";
InputStream stream = MainClass.class.getClassLoader().getResourceAsStream(files);
File f = new File(files);
if(stream == null)
System.out.println("stream is null");
try {
int val = stream.read();
BufferedWriter br = new BufferedWriter(new FileWriter(f));
while(val != -1){
br.write(val);
val = stream.read();
}
stream.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
isInstalling = false;
}
}
它打印“stream is null”并在该行给出错误:stream.read(); 我知道这意味着文件没有正确转换为 InputStream。我犯了一个愚蠢的错误???请帮忙。在此先感谢编辑:我要复制到与 jar 相同的目录中的文件直接在 jar 内。它不在包或任何此类附加目录中。