3

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?

Thanos
  • 594
  • 2
  • 7
  • 28
  • This works for me. Check if the method is being entered. Also, remember that the file will be generated in the project folder. – Christian Tapia Mar 14 '14 at 17:35
  • two situations i can think of: 1- The file is saved in a different location 2-the directory you're writing to is read-only – Mohammad Najar Mar 14 '14 at 17:35
  • 1
    You are using only file name, so path if relevant on directory from which you are running your code. Print value of `file.getAbsoluteFile()` and check if file is there. If it is not there then check your writing permissions. – Pshemo Mar 14 '14 at 17:36
  • I suggest to follow the tutorial: http://docs.oracle.com/javase/tutorial/essential/io/fileio.html – Puce Mar 14 '14 at 17:38
  • @Christian : The method is entered. I didn't included, but there is a printing command at the beginning of the method. – Thanos Mar 14 '14 at 17:42
  • 1
    @Mohammad: The file cannot be found anywhere. I searched with `locate` and `find` linux commands and it doesn't exist. In this directory I can create and delete files. – Thanos Mar 14 '14 at 17:44
  • Did you try `file.getAbsoluteFile()` to see what it returns? Or do you get an empty value? – Mohammad Najar Mar 14 '14 at 17:49
  • @Pshemo : I get not ouptut when I print `file.getAbsoluteFile()`. It seems that I can't get into `try{}` – Thanos Mar 14 '14 at 17:51
  • This methods entire body is in try, so not being able to enter it is the same as not being able to invoke `SAVE_REPORT` method. Can we see how you are invoking it? From what you said it should be invoked "when the button is pushed". Can we see code you are using to connect this method with button? – Pshemo Mar 14 '14 at 17:54
  • Update... A print command after `File file = new File("logKMAX.txt");` returns `Test string logKMAX.txt`. A print command after `bw.close();` returns nothing. – Thanos Mar 14 '14 at 17:56
  • Do you see any stacktrace? Maybe some exception was thrown before `bw.close();` was invoked. – Pshemo Mar 14 '14 at 18:00
  • I also put a print command before `FileWriter fw = new...` and it doesn't print anything... I also tried to remove the if statement, but no luck...`What is a "stacktrace"? – Thanos Mar 14 '14 at 18:06
  • A stacktrace is the result of your `e.printStackTrace()`. It goes to the process' standard error. – fge Mar 14 '14 at 18:11
  • http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors should explain what stack trace is. – Pshemo Mar 14 '14 at 18:14
  • For now lets do some old school simple debugging. Add print statement before each action you are doing in code like `System.out.println("entering try")` before `try{` or `System.out.println("left try-catch blocks")` after your last `catch` block. See which statements will be printed and where your code breaks. – Pshemo Mar 14 '14 at 18:21
  • I put a print command inside `catch` and it's really printed. – Thanos Mar 14 '14 at 18:30
  • Maybe for some reasons you are not seeing output of error stream. Try changing `e.printStackTrace();` to `e.printStackTrace(System.out);` to redirect stacktrace to standard output. Now you have to see some information about error thrown. Update your question with information about this error. – Pshemo Mar 14 '14 at 18:50
  • I'm not sure if I can do that... I am using a platform called Kmax. The way I print is using a report object(`report.setProperty("INSERT", "["+now.format(new Date())+"] Inside catch : \n");`) – Thanos Mar 14 '14 at 18:59
  • Something weird happened... I run the platform using `sudo` rights. It created and saved the file. After that I run again the platform without `sudo` rights and the file was created and saves as well... I tried another computer I got the same behaviour. Once I run `sudo` it works... – Thanos Mar 14 '14 at 19:16
  • @Thanos Which means you don't have permissions to write to this directory. Read more about it, for instance at http://linuxcommand.org/lts0070.php – Pshemo Mar 14 '14 at 19:26

2 Answers2

2

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();
    }
}
fge
  • 119,121
  • 33
  • 254
  • 329
  • My compiler doesn't seem to recognize `Path`, `Paths`, `StandardCharsets`, `StandardOpenOption`, `Files`... Do I have to import anything? – Thanos Mar 14 '14 at 18:02
  • Ah, you still use Java 6? – fge Mar 14 '14 at 18:08
  • No! I use 7! `thanos@thanos-laptop:~$ java -version java version "1.7.0_51" OpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.12.04.2) OpenJDK Server VM (build 24.45-b08, mixed mode)` – Thanos Mar 14 '14 at 18:10
  • OK, but what does `javac -version` say? (note: java**c**, not java) – fge Mar 14 '14 at 18:11
  • @Thanos Add imports to `java.nio.file.*` if you want to use `Files`, `Path`, `Paths`, `StandardOpenOption`. Also `StandardCharsets` is placed at `java.nio.charset`. If you are using IDE like Eclipse just let it import it for you. Just use `Ctrl`+`Shift`+`O`, or press `Source -> Organize imports`. – Pshemo Mar 14 '14 at 18:12
  • @fge : `javac 1.7.0_51` – Thanos Mar 14 '14 at 18:14
  • OK, so as @Pshemo mentions, you are missing imports – fge Mar 14 '14 at 18:14
  • It cannot recognize `import java.nio.charset;` – Thanos Mar 14 '14 at 18:17
  • Since this is a package, this is normal, you need to import the _class_: `import java.nio.charset.StandardCharsets;`. – fge Mar 14 '14 at 18:18
  • And is there a stacktrace? – fge Mar 14 '14 at 18:35
  • Then the file is not where you think it is. Try and `System.out.println(path.toAbsolutePath())` before the `try` block to see where the file is actually created – fge Mar 14 '14 at 18:43
0
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);
                }
            }
        }
    }
}
  • Well this has it own weakness though. The 2 for loops can only process 1-level sub folder. – Sal Joe Dec 02 '19 at 12:26
  • When answering an old question, your answer would be much more useful to other StackOverflow users if you included some context to explain how your answer helps, particularly for a question that already has an accepted answer. See: [How do I write a good answer](https://stackoverflow.com/help/how-to-answer). – David Buck Dec 02 '19 at 12:29
  • Yes sir. I noticed too but it's actually my first post and I fumbled with the interface. Combining the codes and an explanation was difficult for me. I'll get better and heed your advice. Thanks – Sal Joe Dec 03 '19 at 15:31