Write To file with getResource

谁说我不能喝 提交于 2019-12-11 06:23:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!