简体   繁体   中英

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. For one, in your program, you don't verify the return value of .createNewFile() : it doesn't throw an exception on failure...

With the new file API, it is MUCH more simple:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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