Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 字符串替换()给出空指针异常_Java - Fatal编程技术网

Java 字符串替换()给出空指针异常

Java 字符串替换()给出空指针异常,java,Java,我哪里出错了??无论我做什么,它都会在String.replace()上显示空指针异常 我想替换文件中的字符,并将更改的内容写入其他文件。。虽然很简单,但我不会写。请帮忙 package tinku; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and o

我哪里出错了??无论我做什么,它都会在String.replace()上显示空指针异常 我想替换文件中的字符,并将更改的内容写入其他文件。。虽然很简单,但我不会写。请帮忙

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;
        }
    }
}

当您运行while循环时,退出条件是循环在
str
变为
null
时结束,因此当您下次尝试访问
str
时,它将变为null,并给出
NullPointerException

您可以通过在
replaceAll()
代码周围运行类似的
while
循环来修复它,或者可以移动所有内容,直到
replaceAll()
方法调用在
while
循环中为止。(注意:这将询问您是否要为每次事件更换

可能的固定代码:

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.*;

/**
 *
 * @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;
        BufferedReader br = 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 = br.readLine();

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

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

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

        lr.close();

        System.out.println("Do u wish to change the Key Element? Y|N");
        String Dec= br.readLine();
        switch(Dec) {
            case "Y" : {
                System.out.print("Enter String to replace Key with : ");
                String d2;
                d2 = br.readLine();
                lr= new LineNumberReader(new FileReader(f));
                String outputFile = "/home/gajasurve/Desktop/done2.txt";
                PrintWriter pw = new PrintWriter(new FileWriter(outputFile));

                while((str = lr.readLine()) != null) {
                    if(str.contains(Key)) {
                        pw.println(str.replaceAll(Key, d2));
                    } else {
                        pw.println(str);
                    }
                }
                pw.close();
                break;
            }
        }
    }
}

那么我该怎么解决呢?为什么不在一个变量编辑的答案中的if块中指定str值,如果它解决了你的问题,就接受这个答案,否则就把你的疑问添加为注释。我们不能只将
str
的值赋给一个变量,因为可能会出现多次。我们需要一个列表来存储所有这些内容。@Codi我不明白为什么我们不能?@theRoot说我们正在寻找
=“hello”,该文件有两行,分别包含“hello world 1”和“hello world 2”,如果我们将
str
存储在变量Say
storage
,那么第一次它会存储“hello world 1”,但当“hello world 2”也被解读为正数,然后它将通过在其中存储“hello world 2”来覆盖
存储
。在这种情况下,我们将丢失以前必须替换的值,因此我们需要使用列表来存储所有事件。