-1
哪裏Iam出錯?無論我做什麼它說String.replace空指針異常() 我想從文件替換一個Charecter並將改變的內容寫入其他文件..即使它很容易,我無法寫它。請幫助!字符串替換()給出空指針異常
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;
}
}
}
那麼,怎樣才能解決呢? –
爲什麼不分配變量中的str值如果塊中的變量 – theRoot
編輯答案,接受答案,如果它解決了你的問題,否則添加你的疑問作爲評論。 我們不能只將'str'的值賦給一個變量,因爲可能有多個事件。我們需要一個列表來存儲它們。 – Codi