简体   繁体   English

用Java读取和写入同一个文件

[英]Reading and writing from and to the same file in Java

I want to read from criteria.txt file, to tokenize and append at the end of the same file the tokens. 我想从criteria.txt文件中读取,以标记化并在同一文件的末尾追加令牌。 The program throws an exception: No file found! 该程序抛出异常: No file found! I do not know where my mistake is. 我不知道我的错误在哪里。 Any suggestion would help me. 任何建议都会对我有所帮助。 Thank you in advance! 先感谢您!

Here is my code: 这是我的代码:

import java.io.*;
import java.util.StringTokenizer;

public class Test
{
    private FileReader fr;
    private BufferedReader br;
    private FileWriter fw;
    private BufferedWriter bw;
    private StringTokenizer strtok;
    private String s;

    //constructor
    public Test()  
    {
        try
        {
            fw=new FileWriter("criteria.txt", true);
            bw=new BufferedWriter(fw);

            try
            {
                fr=new FileReader("criteria.txt");
                br=new BufferedReader(fr);

                while((s=br.readLine())!=null)
                {
                    strtok=new StringTokenizer(s," ");
                    while(strtok.hasMoreTokens())
                    {
                        bw.write("\n"+strtok.nextToken());
                    }
                    br.close();
                }
            }
            catch(FileNotFoundException e)
            {
                System.out.println("File was not found!");
            }
            catch(IOException e)    
            {
                System.out.println("No file found!");
            }

            bw.close();
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error1!");
        }
        catch(IOException e)    
        {
            System.out.println("Error2!");
        }
    }   

    public static void main(String[] args) 
    {
        Test t=new Test();
    }
}

You need to close your reader after you have finished reading the file ie after the while loop. 完成读取文件后,即在while循环后,您需要关闭阅读器。 Currently, you are closing it after reading the first line, which causes an " IOException: Stream closed " when it tries to read the second line. 目前,您在读取第一行后关闭它,当它尝试读取第二行时会导致“ IOException: Stream closed ”。

Change to: 改成:

while((s=br.readLine())!=null)
{
    strtok=new StringTokenizer(s," ");
    while(strtok.hasMoreTokens())
    {
        bw.write("\n"+strtok.nextToken());
    }
    //br.close(); <----- move this to outside the while loop
}
br.close();

Your greatest undoing is placing the br.close(); 你最大的撤销是放置br.close(); inside the while() loop: You are telling the computer each time it writes to the file to close it immediately, hence the file remained closed and computer will never find it during the next iteration/ execution of the loop. while()循环内部:每次写入文件时都要告诉计算机立即关闭它,因此文件保持关闭状态,计算机在循环的下一次迭代/执行期间永远不会找到它。 However, I have edit the initial program to this: 但是,我已经编辑了初始程序:

import java.io.*;
import java.util.StringTokenizer;

public class Test
{
    private FileReader fr;
    private BufferedReader br;
    private FileWriter fw;
    private BufferedWriter bw;
    private StringTokenizer strtok;
    private String s;

    //constructor
    public Test()  
    {
        try
        {
            fw=new FileWriter("criteria.txt", true);
            bw=new BufferedWriter(fw);

            try
            {
                fr=new FileReader("criteria.txt");
                br=new BufferedReader(fr);

                **while((s=br.readLine())!=null)
                {
                    strtok=new StringTokenizer(s," ");
                    while(strtok.hasMoreTokens())
                    {
                        bw.write("\n"+strtok.nextToken());
                    }

                }
                     br.close();
            }**
            catch(FileNotFoundException e)
            {
                System.out.println("File was not found!");
            }
            catch(IOException e)    
            {
                System.out.println("No file found!");
            }
            bw.close();
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error1!");
        }
        catch(IOException e)    
        {
            System.out.println("Error2!");
        }
    }   

    public static void main(String[] args) 
    {
        Test t=new Test();
    }
}

The folder or directory the file exist doesn't matter in this case as the program will create a new file named "criteria.txt" in the same folder as the java program; 在这种情况下,文件所在的文件夹或目录无关紧要,因为程序将在与java程序相同的文件夹中创建一个名为“criteria.txt”的新文件。 however, you will have to open the file with a text editor to add/ append some data as the file will be blank initially. 但是,您必须使用文本编辑器打开文件以添加/附加一些数据,因为文件最初将为空白。 Subsequent run of the program will now append the already inserted content(s) as a concatenation string on a new line. 该程序的后续运行现在将已插入的内容作为新行上的串联字符串附加。 A new line will be produced each time the program is run. 每次运行程序时都会生成一个新行。 Hope this helps. 希望这可以帮助。

In my opinion you can't do that. 在我看来,你不能这样做。 You can't open the same file to read and write at the same time. 您无法同时打开同一个文件进行读写。 You have to open and save the file information in a data structure and then close it. 您必须在数据结构中打开并保存文件信息,然后将其关闭。 Then you have to work with the data structure in memory and open the file to write results. 然后,您必须使用内存中的数据结构并打开文件以写入结果。 And when you finish to write you should close it. 当你完成写作时,你应该关闭它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM