在我的客户端/服务器应用程序中,我需要发送一些文件(.txt
, .doc
等)从客户端到服务器。当我在 Eclipse 中运行代码时,它可以工作,但是当我导出 Applet 的签名 JAR 时,它不能工作。它抛出一个FileNotFoundException
。我尝试以多种方式保存文件但没有成功。
public static boolean saveFile(File sourceFile) throws IOException {
DirectoryChooserDialog dialog = new DirectoryChooserDialog();
filePath = dialog.getDestinationFolder();
if (filePath != null) {
InputStream inputFile = ClassLoader.getSystemResourceAsStream(""+sourceFile);
filePath += File.separator + sourceFile.getName();
FileOutputStream outputFile = new FileOutputStream(filePath);
int byteLetti = 0;
while ((byteLetti = inputFile.read(buffer)) >= 0) {
outputFile.write(buffer, 0, byteLetti);
outputFile.flush();
}
inputFile.close();
outputFile.close();
return true;
} else
return false;
}
使用的替代代码:
FileInputStream inputFile = new FileInputStream(sourceFile);
Or
InputStream inputFile = ClassLoader.class.getResourceAsStream(""+sourceFile);
Or
InputStream inputFile = FileSaving.class.getResourceAsStream(""+sourceFile);
原始代码和每个替代代码都可以在 Eclipse 中工作,并在导出时停止工作。
此代码正在查找类路径上的文件。如果那里没有文件,则会抛出 FNF。当您在 Eclipse 中工作时,您的文件可能位于 src 中,因此它会被复制到 bin 中。将文件存档到 jar 后,您可以访问它getResource
or getResourceAsStream
InputStream inputFile = this.getClass().getClassLoader().getResourceAsStream(sourceFile.getName())
或使用网址。例如
URL url = new URL("jar:file:/c:/path/to/my.jar!/myfile.txt");
JarURLConnection conn = (JarURLConnection)url.openConnection();
InputStream inputFile = conn.getInputStream();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)