问题
I use This methods to Write to a text file(use getResource()... to use in JAR file). My files are in Classpath, Here is my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class JarWrite {
public JarWrite(){
writethis();
}
public void writethis(){
try{
InputStreamReader isReader= new InputStreamReader(this.getClass().getResourceAsStream("AllBookRecords.txt"));
BufferedReader br = new BufferedReader(isReader);
PrintWriter writer1=new PrintWriter(new File(this.getClass().getResource("Boutput.txt").getPath()));
String Bs;
while( (Bs=br.readLine()) != null ){
writer1.println(Bs);
}
writer1.close();
br.close();
} catch(FileNotFoundException fnfe){
} catch(IOException ioe){
ioe.printStackTrace();
}
}
public static void main(String[] args){
new JarWrite();
}
}
回答1:
You can't modify resources from CLASSPATH. They are read only. Period.
See also: Java OutputStream equivalent to getClass().getClassLoader().getResourceAsStream().
回答2:
Try changing:
public void writethis
to
public static void writethis
来源:https://stackoverflow.com/questions/14446974/write-to-file-with-getresource