How to write a file to a directory?
I have tried with my class to achieve it : Output : Solution 2: Just use this String pathTemp=System.getProperty(«user.dir»); //it will give the root directory of where your program runs String String pathTemp=pathTemp+»/target/»+fileName; //here file name from the argument Path path=Paths.get(pathTemp); Files.write(path,list,Charset.defaultCharset()); Note I use the two-argument constructor for which takes a representing the directory, and a name for a file inside that directory.
How to write a file to a directory?
Some remarks about your code:
- Create the parent directory before the file . You cannot create a file in a non existent directory. file.getParentFile().mkdirs();
- Remove the FileOutputStream code . You are using both a FileWriter and FileOutputStream at the same time for the same file. This is a mistake as one may overwrite the other, causing the file to be immediately cleared after being written to.
- createNewFile() is not necessary . The FileWriter or FileOutputStream can create it’s own file as long as the directory exists (see #1).
- Close the writer in a finally block so that you are guaranteed the underlying stream is closed even if an exception occurs during writing.
I’m not sure what the isDirectory check is for. If it exists, surely it would be a file and not a directory. Either way, file.exists() && file.isDirectory() is unnecessary as isDirectory already checks for existence.
Updated code:
public static void nJSON(String username ) < File file = new File("src/jsonFiles/" + username + ".json"); if (file.isDirectory()) < System.err.println(username + ".json exist and is a directory."); return; >if(!file.getParentFile().exists() && !file.getParentFile().mkdirs()) < System.err.println("Failed to create directory " + file.getParent()); return; >FileWriter writer = null; try < json.put("Username", username); json.put("Password", mainFiles.windowsSrc.UserInfo.password); writer = new FileWriter(file); writer.write(json.toJSONString()); writer.close(); System.out.println(username + ".json created."); >catch(IOException e) < e.printStackTrace(); >finally < if(writer != null) < try < writer.close(); >catch(IOException ignore) < >> > >
import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; public class WriteFile < public static void main(String[] args) < nJSON("test"); >public static void nJSON(String username) < File file = new File("/home/ivan/Downloads/" + username + ".json"); try < if (file.exists() && file.isDirectory()) < System.out.println(username + ".json exist."); >else < String content = "testing"; file.createNewFile(); FileWriter writer = new FileWriter(file); FileOutputStream os = new FileOutputStream(file); writer.write(content); writer.flush(); os.close(); writer.close(); System.out.println(username + ".json created."); >> catch (IOException e) < e.printStackTrace(); >> >
Just replace home/ivan/Downloads/ with a valid directory path. It is basically your code with out simple json. It works on my machine so I suspect you are trying to write to directory that does not exists.
Java — How to write a file to a directory?, Sorted by: 6. Some remarks about your code: Create the parent directory before the file. You cannot create a file in a non existent directory. file.getParentFile ().mkdirs (); Remove the FileOutputStream code. You are using both a FileWriter and FileOutputStream at the same time for the same file. This is …
How to write a file to a particular folder in java?
to store file to the folder screenshot , change the variable
String ref = "absolute_path_of_folder/" + df.format(date); // like "C:/screenshot/" + df.format(date);
it will save file to that folder.
Have you tried this? Note I use the two-argument constructor for File which takes a File representing the directory, and a name for a file inside that directory. I uncommented your lines describing which directory to save to, and used that directory.
SimpleDateFormat df=new SimpleDateFormat("dd-MM-yy H-m'.png'"); //Setting the date format Date date=new Date(); //Getting the current date and time String ref=df.format(date); //Formatting the current date in the SDF constructor's format String dirname="M:\\Java\\bin\\screenshot\\"; System.out.println(ref); //Testing whether the current date is getting displayed in the desired format Robot robot = new Robot(); //Instanciating the Robot class Rectangle captureSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); //Declaring a rectangle with size of the screen BufferedImage bufferedImage = robot.createScreenCapture(captureSize); //Capturing the screenshot and save it in Buffered image object File dir = new File(dirname); File filen = new File("M:\\Java\\bin\\screenshot\\temp.png"); File filename = new File(filen, ref); ImageIO.write(bufferedImage, "png" , filename); //writing the image to a file called filename
The package name is same as the name of the destination folder. Changing the package name or the folder name, every method listed is working fine
How to create a file in a directory in java?, 11 Answers. String path = «C:» + File.separator + «hello» + File.separator + «hi.txt»; // Use relative path for Unix systems File f = new File …
Java: How to create & write file to maven target directory
The first / was causing a problem in the string. You have to get the full string without that.
I have tried with my class to achieve it :
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath(); path = path.substring(1, path.length()) + "file.txt"; System.out.println(path); Path out = Paths.get(path); System.out.println(out.isAbsolute());
F:/software/workspace/file.txt true
String pathTemp=System.getProperty(«user.dir»); //it will give the root directory of where your program runs
String String pathTemp=pathTemp+»/target/»+fileName; //here file name from the argument
How to check write permissions of a directory in java?, Java has its own permission model revolving around the use of an AccessController and Permission classes. The permissions are granted to a …