가
나는 비슷한 문제로 실행했습니다, 그리고 당신이에 익숙하기 때문에, 나는이 시작하자이
피터, jar 파일로 압축 된 파일을 읽을 수 없으므로 원래 코드 에서처럼 액세스하면 작동하지 않습니다. 대신, Java가 스트림을 제공하도록 Java에 요청해야합니다 (많은 다른 사람들이 유용하게 지적한 것처럼). Java가 제공하는 방법을 알고 있습니다.
이제 파일을 실제로 출력하는 것은 고통입니다. 여기에 제가 작성한 코드가 있습니다. 물론 다른 소스에서 찾아 볼 수 있습니다. 필요에 따라 예외를 기입하십시오! =)
InputStream in = null;
in = this.getClass().getResourceAsStream("/main.cc");
File outputFile = createMainOutputFile();
OutputStream out = null;
try {
out = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
System.out.println(outputFile + " was not found!");
e.printStackTrace();
}
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
try {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
실제로 파일 조각을 출력해야합니다. 슬픈 사실을 알고 있습니다. 정말 기대했던대로하고 싶습니다. 인생을 훨씬 쉽게 만들어 줄 것입니다. createMainOutputFile() 호출이 혼동 될 수있는 유일한 방법은, 그래서 여기 ... 너무에 대한 코드의
private File createMainOutputFile() {
File directoryPath = new File(mainOutputFolder);
directoryPath.mkdirs();
File newFile = new File (mainOutputFolder + "main.cc");
try {
newFile.createNewFile();
} catch (IOException e) {
System.out.println("failed To create new file.");
e.printStackTrace();
}
return newFile;
}
행운을 빕니다!
편집 : XML 파서로 파싱을한다는 것을 알게되었으므로, 적어도 아파치 파서 (apache 파서)를 사용하고 있다면 실제로는 그냥 것 파일과 같은 InputStream를 받아이 일반적인 문제에
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
try {
docBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//Here we supply the inputStream instead of the file...
doc = docBuilder.parse(inputStream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Node xmlRoot = doc.getFirstChild();
아래 답변을 싫어한다는 것을 알기 때문에 파일이 jar/jars/war에 패키지로 제공되는지 여부를 알고 싶습니다. 어떤 경우에는 클래스 로더에서 리소스를 검색하는 것과 관련된 아래 답변이 작동해야합니다. 응용 프로그램과 함께 번들되지 않은 경우 클래스로드 메커니즘을 통해 조회하면 도움이되지 않습니다. – Yaneeve
AFAIK 있습니다. Eclipse를 사용하여 프로젝트를 OS X 응용 프로그램 번들로 내보내고 xml 파일이있는 res 폴더를 번들에 추가합니다. 이제 번들을 살펴보면 JAR 파일이 표시됩니다. 추출한 파일에는 res 폴더가 들어 있습니다. 그렇습니다. 파일은 확실히 JAR 파일 내에 패키지되어 있습니다. 편집 : 나는 대답을 싫어하는 것이 아니라, 반대로 나는 모든 코멘트에 대해 감사하고있다. 그러나 그들은 단지 내 경우에는 효과가없는 것 같다. – Peter
파일 이름뿐만 아니라 항아리 내의 경로. 파일 이름이 file.xml이고 res 폴더에 있고 res 폴더가 jar 파일의 최상위 폴더 인 경우 "res/file.xml"에 액세스해야합니다. – Yaneeve