有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中写入文件。帮我编码

我正在向这个方法传递一个文件路径,这个方法会将文件写入txt文件。但当我运行这个程序时,它并没有写满,我不知道我在哪里犯了错误

public void content(String s) {
  try { 
    BufferedReader br=new BufferedReader(new FileReader(s)); 
    try {
      String read=s;
      while((read = br.readLine()) != null) {    
        PrintWriter out = new PrintWriter(new FileWriter("e:\\OP.txt"));
        out.write(read);
        out.close();
      }
    } catch(Exception e) { }    
  } catch(Exception e) { }
}

共 (3) 个答案

  1. # 1 楼答案

    试试这个

    public void content(String s) throws IOException { 
            try (BufferedReader br = new BufferedReader(new FileReader(s));
                    PrintWriter pr = new PrintWriter(new File("e:\\OP.txt"))) {
                for (String line; (line = br.readLine()) != null;) {
                    pr.println(line);
                }
            }
    }
    
  2. # 2 楼答案

    在完成之前关闭流。所以要么把它放进

    <code>
    finally {
    out.close();
    }
    </code>
    
    or see this simple example
    
    <code>try {
        String content = s;
        File file = new File("/filename.txt");
    
        // if file doesnt exists, then create it
        if (!file.exists()) {
        file.createNewFile();
        }
    
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();
        System.out.println("Done");
        } catch (IOException e) {
        e.printStackTrace();
        }
        }
    </code>
    
  3. # 3 楼答案

    您不应该每次都在循环中创建PrintWriter:

    public void content(String s) {
       BufferedReader br=new BufferedReader(new FileReader(s));
    
       try {
          PrintWriter out=new PrintWriter(new FileWriter("e:\\OP.txt"));
          String read=null;
    
          while((read=br.readLine())!=null) {
             out.write(read);
          }
       } catch(Exception e) {
          //do something meaningfull}
       } finally {
          out.close();
       }
    }
    

    另外,正如其他人提到的,添加finally块,不要静默地捕获异常,并遵循Java编码约定