简体   繁体   English

如何在java中保存文件

[英]How to save a file in java

I am trying to create a file from a log report.我正在尝试从日志报告创建一个文件。 To save the file I've created a button.为了保存文件,我创建了一个按钮。 When the button is pushed, the following code is executed:当按钮被按下时,执行以下代码:

public void SAVE_REPORT(KmaxWidget widget){//save
  try {
    String content = report.getProperty("TEXT");
    File file = new File("logKMAX.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();
  } catch (IOException e) {
    e.printStackTrace();
  }
} //SAVE_REPORT

I have no compilation errors, but there isn't any file saved.我没有编译错误,但没有保存任何文件。

Any idea on what might be wrong?关于可能出什么问题的任何想法?

Use the new file API.使用新的文件 API。 For one, in your program, you don't verify the return value of .createNewFile() : it doesn't throw an exception on failure...一方面,在你的程序中,你没有验证.createNewFile()的返回值:它不会在失败时抛出异常......

With the new file API, it is MUCH more simple:使用新的文件 API,它要简单得多:

public void saveReport(KmaxWidget widget)
    throws IOException
{
    final String content = report.getProperty("TEXT");
    final Path path = Paths.get("logKMAX.txt");

    try (
        final BufferedWriter writer = Files.newBufferedWriter(path,
            StandardCharsets.UTF_8, StandardOpenOption.CREATE);
    ) {
        writer.write(content);
        writer.flush();
    }
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class moveFolderAndFiles
{
    public static void main(String[] args) throws Exception 
    {   
        File sourceFolder = new File("c:\\Audio Bible");

        copyFolder(sourceFolder);
    }
    private static void copyFolder(File sourceFolder) throws Exception
    {
        File files[] = sourceFolder.listFiles();
        int i = 0;

        for (File file: files){
            if(file.isDirectory()){
                File filter[] = new File(file.getAbsolutePath()).listFiles();
                for (File getIndividuals: filter){
                    System.out.println(i++ +"\t" +getIndividuals.getPath());
                    File des = new File("c:\\audio\\"+getIndividuals.getName());
                    Files.copy(getIndividuals.toPath(), des.toPath(), StandardCopyOption.REPLACE_EXISTING);
                }
            }
        }
    }
}

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

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