1

Hey I've been trying to implement a programm which takes values from a GUI and gives them to another programm in a class written by me which should output a txt file. The GUI and the other class work fine but I cant seem to get the values from the GUI to the other class or the class member simply doesn't start. I have this so far:

import java.io.*;
//
//some code
//
public static void SaveTextToFile(String Name,String  Spec, String Text ){

    try{
        File file = new File("user.dir"+ File.separator + Name + File.separator + Spec + "Text.txt");
        file.getParentFile().mkdir();
        FileWriter writer = new FileWriter(file);
        writer.write(Text);
        writer.flush();
        writer.close();
    } catch
      (IOException e)  {}
    }

...

But somehow not even a file or a directory is created. Any ideas?

M. St.
  • 63
  • 6
  • Check what `file.getParentFile().mkdir();` is returning `true` or `false`. If `false` try replacing it with `file.getParentFile().mkdirs();` – Abdul Fatir Jun 25 '16 at 09:23

3 Answers3

1

If you want to create the entire folder structure, you'll have to use mkdirs not mkdir.

Use file.getParentFile().mkdirs();

mkdir()

Creates the directory named by this abstract pathname.

mkdirs()

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

Read this answer.

Community
  • 1
  • 1
Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
1

I fixed the problem with the appache commons io FileUtils package.

Now i have:

public static void SaveTextToFile(String Name,String  Spec, String Text ){

    try{
        File file = new File(Name + File.separator + Spec + "Text.txt");
        org.apache.commons.io.FileUtils.forceMkdirParent(file);
        org.apache.commons.io.FileUtils.writeStringToFile(file, Text,  "utf8");
    } catch
      (IOException e)  {}
    }

And it works wonderfully

Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
M. St.
  • 63
  • 6
0

try

File file = new File(
        System.getProperty("user.home") + File.separator +  Name  + File.separator +  Spec  + "Text.txt");

instead of "user.dir" if you want to create a file in the user's folder structure

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97