1

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();
    }    
    }
Rohit Jain
  • 203,151
  • 43
  • 392
  • 509
Sajad
  • 2,172
  • 11
  • 46
  • 87

2 Answers2

5

You can't modify resources from CLASSPATH. They are read only. Period.

See also: Java OutputStream equivalent to getClass().getClassLoader().getResourceAsStream().

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 324,247
  • 67
  • 682
  • 662
-1

Try changing:

public void writethis

to

public static void writethis
Aleksandr M
  • 23,988
  • 12
  • 67
  • 136
Mike
  • 7
  • 1