Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.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 如何将字符串添加到文件的第n行_Java_Json_File - Fatal编程技术网

Java 如何将字符串添加到文件的第n行

Java 如何将字符串添加到文件的第n行,java,json,file,Java,Json,File,因此,我尝试将字符串添加到JSON文件的特定行(例如,包含单词的行)中 我的主要问题是,在访问文件后,我不知道如何到达该特定行并将字符串放入其中 BufferedWriter out = new BufferedWriter(new FileWriter(f,true)); String newLine=crp.makeLine(); BufferedReader br= new BufferedReader(new FileRea

因此,我尝试将字符串添加到JSON文件的特定行(例如,包含单词的行)中

我的主要问题是,在访问文件后,我不知道如何到达该特定行并将字符串放入其中

BufferedWriter out = new BufferedWriter(new FileWriter(f,true));
                String newLine=crp.makeLine();
                BufferedReader br= new BufferedReader(new FileReader(f));
                for (int i=0;i<=lineCounter;i++){
                    br.readLine();
                    if(i==lineCounter){
                        out.write(newLine);
                    }
                }
BufferedWriter out=new BufferedWriter(new FileWriter(f,true));
字符串newLine=crp.makeLine();
BufferedReader br=新的BufferedReader(新文件读取器(f));

对于(int i=0;i所发生的事情是有意义的,因为您确实在文件末尾插入了“换行符”,以正确的方式,您应该获得文件的所有内容,将其存储在StringBuffer中,然后进行修改,然后您可以重写文件。 下面是一个演示代码:

try {
        // input the file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader(f));
        StringBuffer inputBuffer = new StringBuffer();

        while ((line = file.readLine()) != null) {
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();
        String inputStr = inputBuffer.toString();

        System.out.println(inputStr); // display the original file for debugging

            int wordIndex = inputStr.indexOf('the word')
            inputStr = inputStr.substring(0, wordIndex ) + "new string" + inputStr.substring(wordIndex , inputStr.length());             

        // display the new file for debugging
        System.out.println("----------------------------------\n" + inputStr);

        // write the updated content with the new string OVER the same file
        FileOutputStream fileOut = new FileOutputStream(f);
        fileOut.write(inputStr.getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }

请检查代码是否有错误,因为这只是一个演示代码。

发生的事情是有意义的,因为您确实在文件末尾插入了“换行符”,以正确的方式,您应该获取文件的所有内容,将其存储在StringBuffer中,然后进行修改,然后可以重写文件。 下面是一个演示代码:

try {
        // input the file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader(f));
        StringBuffer inputBuffer = new StringBuffer();

        while ((line = file.readLine()) != null) {
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();
        String inputStr = inputBuffer.toString();

        System.out.println(inputStr); // display the original file for debugging

            int wordIndex = inputStr.indexOf('the word')
            inputStr = inputStr.substring(0, wordIndex ) + "new string" + inputStr.substring(wordIndex , inputStr.length());             

        // display the new file for debugging
        System.out.println("----------------------------------\n" + inputStr);

        // write the updated content with the new string OVER the same file
        FileOutputStream fileOut = new FileOutputStream(f);
        fileOut.write(inputStr.getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }

请检查代码是否有错误,因为这只是一个演示代码。

您的代码正在正确读取要写入的行。但是,您在附加模式下打开的写入程序将只在文件末尾写入。您在文件中读取的位置与在f中写入的位置之间没有关联伊莱

如果你把一个文件看作一个数组,你就不能任意地写入中间的任何部分(即使用随机访问),而不重写现有的内容。至少你必须把所有的东西从你想要插入的点复制到最后,写下你想插入的东西,然后把你复制的所有东西追加到结尾。


如果要避免将整个文件读入内存,可以逐行将文件处理为临时文件,然后如果成功,则在最后将临时文件复制到原始文件上

    public void insertLine(File f, String newLine, int lineCounter) throws IOException {
        File temp = File.createTempFile(f.getName(), ".temp");
        temp.deleteOnExit();

        try (PrintWriter writer = new PrintWriter(new FileWriter(temp))) {
            try (LineNumberReader reader = new LineNumberReader(new FileReader(f))) {
                reader.lines().forEachOrdered(line -> {
                    if (reader.getLineNumber() == lineCounter) {
                        writer.println(newLine);
                    }
                    writer.println(line);
                });
            }
        }

        Files.copy(temp.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
        temp.delete();
    }
如果您需要更多的灵活性或添加、编辑或删除多行的能力,您可以考虑传入一个侦听器/函数

    public interface LineModifierFunction {
        boolean line(String line, int lineNumber, PrintWriter writer);
    }
其中,返回值确定是否应写入原始行以及是否允许函数写入自己的行

    public void insertLine(File f, LineModifierFunction listener) throws IOException {
        File temp = File.createTempFile(f.getName(), ".temp");
        temp.deleteOnExit();

        try (PrintWriter writer = new PrintWriter(new FileWriter(temp))) {
            try (LineNumberReader reader = new LineNumberReader(new FileReader(f))) {
                reader.lines().forEachOrdered(line -> {
                    if (listener.line(line, reader.getLineNumber(), writer)) {
                        writer.println(line);
                    }
                });
            }
        }

        Files.copy(temp.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
        temp.delete();
    }
在您的示例中,这将被称为:

        insertLine(f, (l, n, p) -> {
            if (n == lineCounter) {
                p.println(crp.makeLine());
            }
            return true;
        });
还是用旧币

        insertLine(f, new LineModifierFunction() {
            public boolean line(String l, int n, PrintWriter p) {
                if (n == lineCounter) {
                    p.println(crp.makeLine());
                }
                return true;
            }
        });


最后,对于JSON有效负载,我真的不推荐这种方法。这种算法假设JSON的格式是每行一个字段,没有多行值。最好使用JSON解析器阅读,插入新节点或修改现有值,然后写入对象返回为JSON。
考虑查看Jackson ObjultMappor或GSON。

您的代码正在正确地读取要写入的行。然而,您在附件模式中打开的作者将只在文件的末尾写入。在文件中读取的位置与文件中写入的位置之间没有相关性。

如果你把一个文件看作一个数组,你就不能任意地写入中间的任何部分(即使用随机访问),而不重写现有的内容。至少你必须把所有的东西从你想要插入的点复制到最后,写下你想插入的东西,然后把你复制的所有东西追加到结尾。


如果要避免将整个文件读入内存,可以逐行将文件处理为临时文件,然后如果成功,则在最后将临时文件复制到原始文件上

    public void insertLine(File f, String newLine, int lineCounter) throws IOException {
        File temp = File.createTempFile(f.getName(), ".temp");
        temp.deleteOnExit();

        try (PrintWriter writer = new PrintWriter(new FileWriter(temp))) {
            try (LineNumberReader reader = new LineNumberReader(new FileReader(f))) {
                reader.lines().forEachOrdered(line -> {
                    if (reader.getLineNumber() == lineCounter) {
                        writer.println(newLine);
                    }
                    writer.println(line);
                });
            }
        }

        Files.copy(temp.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
        temp.delete();
    }
如果您需要更多的灵活性或添加、编辑或删除多行的能力,您可以考虑传入一个侦听器/函数

    public interface LineModifierFunction {
        boolean line(String line, int lineNumber, PrintWriter writer);
    }
其中,返回值确定是否应写入原始行以及是否允许函数写入自己的行

    public void insertLine(File f, LineModifierFunction listener) throws IOException {
        File temp = File.createTempFile(f.getName(), ".temp");
        temp.deleteOnExit();

        try (PrintWriter writer = new PrintWriter(new FileWriter(temp))) {
            try (LineNumberReader reader = new LineNumberReader(new FileReader(f))) {
                reader.lines().forEachOrdered(line -> {
                    if (listener.line(line, reader.getLineNumber(), writer)) {
                        writer.println(line);
                    }
                });
            }
        }

        Files.copy(temp.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
        temp.delete();
    }
在您的示例中,这将被称为:

        insertLine(f, (l, n, p) -> {
            if (n == lineCounter) {
                p.println(crp.makeLine());
            }
            return true;
        });
还是用旧币

        insertLine(f, new LineModifierFunction() {
            public boolean line(String l, int n, PrintWriter p) {
                if (n == lineCounter) {
                    p.println(crp.makeLine());
                }
                return true;
            }
        });


最后,对于JSON有效负载,我真的不推荐这种方法。这种算法假设JSON的格式是每行一个字段,没有多行值。最好使用JSON解析器阅读,插入新节点或修改现有值,然后写入对象返回为JSON。
考虑一下Jackson ObjultMappor或GSON。< /P>一个问题:InPutsR=输入Strut.String(0,WordDeq)+“新String”+ EndoStr.String(WordDe指标,X.LangTh());在这行中,变量x代表什么?“x”是指“输入”。一个问题:inputStr=inputStr.substring(0,wordIndex)+“new string”+inputStr.substring(wordIndex,x.length());在这一行中,变量x代表什么?x指的是“inputStr”,我刚刚修复了错误。