vendredi 10 juillet 2015

String Replace() giving null pointer exception

Where Iam Going Wrong?? No Matter What I do It Says Null Pointer Exception on String.replace() I want To replace a Charecter From File And Write The Changed Content To Other File.. even though its easy i am unable to write it.Help Please!

   package tinku;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Scanner;

/**
 *
 * @author gajasurve
 */
public class Tinku {
    static int i;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        // TODO code application logic here
        String str;

        final String Y;
        String Key;
         FileOutputStream fos = new FileOutputStream("/home/gajasurve/Desktop/done2.txt");
            DataOutputStream output = new DataOutputStream(fos);

        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));



   System.out.println("\n Enter Complete File Path with Extension (ex: /home/gajasurve/Desktop/info.txt)  : ");
   String Source;
   Source=r.readLine();

   System.out.print("Enter Key Element to Find In the File ");
         Key=r.readLine();




File f= new File(Source);


LineNumberReader lr= new LineNumberReader(new FileReader(f));

while((str=lr.readLine())!=null)
{
  if(       str.contains(Key))
  {
      i=lr.getLineNumber();
      System.out.print("The Entered Key Element Can B Found In " + i + "   Line");
  } 
}

System.out.println("Do u wish to change the Key Element? Y|N");
String Dec= r.readLine();
switch(Dec){
    case "Y" :

    System.out.print("Enter New Key Element to Replace");


   String d2;
        d2 = r.readLine();

            str= str.replaceAll(Key, d2);  //NPE here
    System.out.println(str);


        break;
}


}

    }

Aucun commentaire:

Enregistrer un commentaire