Team I'm trying to get all the paths from a directory and save all the directorys and files inside a txt file with the date.
Now I get all the directorys and files with file.getAbsolutePath(), but is only writing just a few paths.
File directory = new File(directoryName);
File[] fList = directory.listFiles();
String yourDesktopPath = System.getProperty("user.home") + "\\Desktop\\";
PrintWriter writer = new PrintWriter(yourDesktopPath+"the-file-name.txt", "UTF-8");
try {
for (File file : fList){
if (file.isFile()){
System.out.println(file.getAbsolutePath());
writer.write(file.getAbsolutePath());
} else if (file.isDirectory()){
listFilesAndFilesSubDirectories(file.getAbsolutePath());
}
}
writer.flush();
} finally {
writer.close();
}
You can simply use java.nio.file.Files and it will do the recursive looping for you, you can use it like this:
Files.walk(Paths.get("your_path"))
.map(path -> path.toAbsolutePath().toString())
.forEach(writer::write);
new PrintWriter(yourDesktopPath+"the-file-name.txt", "UTF-8"); truncates the file, erasing whatever you previously wrote to it.
You need to append to your file. FileOutputStream has a constructor which allows you to specify it:
PrintWriter writer = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(yourDesktopPath + "the-file-name.txt", true),
StandardCharsets.UTF_8));
Related
This question already has answers here:
To create a new directory and a file within it using Java
(2 answers)
Closed 4 years ago.
I want to write a new file inside a folder that currently does not exist.
I use it like this:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
I get the file filename.txt under a folder called dir1.dir2.
I need dir1/dir2:
How can I achieve this?
Please do not mark this question as duplicate because I didn't get what I need after a reseach.
UPDATE 1
I am using Jasper Report with Spring Boot to export a pdf file.
I need to create the file under a directory name the current year. Under this folder, I need to create a directory called the current month, and under this directory the pdf file should be exported. Example :
(2018/auguest/report.pdf )
I am using LocalDateTime to get year and month
Here is a portion of my code :
ReportFiller reportFiller = context.getBean(ReportFiller.class);
reportFiller.setReportFileName("quai.jrxml");
reportFiller.compileReport();
reportFiller = context.getBean(ReportFiller.class);
reportFiller.fillReport();
ReportExporter simpleExporter = context.getBean(ReportExporter.class);
simpleExporter.setJasperPrint(reportFiller.getJasperPrint());
LocalDateTime localDateTime = LocalDateTime.now();
String dirName = simpleExporter.getPathToSaveFile() + "/"+
localDateTime.getYear() + "/" + localDateTime.getMonth().name();
File dir = new File(dirName);
dir.mkdirs();
String fileName = dirName + "/quaiReport.pdf";
simpleExporter.exportToPdf(fileName, "");
Here is what I get :
Try below code which will work as per your expectation
File dir = new File("C:\\Users\\username\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newFile = new FileWriter(file);
You need to create folder structure first and file next
You need to create directory first then create file:
Like this:
String dirName = "/" + localDateTime.getYear() + "/" + localDateTime.getMonth().name();
File file = new File(dirName);
file.mkdirs();
file = new File(file.getAbsolutePath()+"/quriReport.pdf");
file.createNewFile();
If you go your project directory you see 2018/August/quriReport.pdf
But IDE show subfolder with . if there is only one subfolder.
At first, create the directories, then create a new file to write.
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
class TestDir {
public static void main(String[] args) {
String dirPath = "C:\\user\\Desktop\\dir1\\dir2\\";
String fileName = "filename.txt";
Path path = Paths.get(dirPath);
if(!Files.exists(path)) {
try {
Files.createDirectories(path);
} catch (IOException e) {
e.printStackTrace();
}
}
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(dirPath + fileName), "utf-8"))) {
writer.write("something");
} catch (IOException e) {
e.printStackTrace();
}
}
}
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
Files.createDirectories(file.getParentFile().toPath());
FileWriter writer = new FileWriter(file);
writer.write("jora");
writer.close();
I'm trying to create sub directories in my apps cache folder but when trying to retrieve the files I'm getting nothing. I have some code below on how I created the sub directory and how I'm reading from it, maybe I'm just doing something wrong (well clearly I am lol) or maybe this isn't possible? (though I haven't seen anywhere that you can't). thank you all for any help!
creating the sub dir
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
File file2 = new File(file, each_filename);
Toast.makeText(getApplicationContext(), file2.toString(), Toast.LENGTH_SHORT).show();
stream = new FileOutputStream(file2);
stream.write(bytes);
reading from it
File file = new File(context.getCacheDir(), "SubDir");
File newFile = new File(file, filename);
Note note;
if (newFile.exists()) {
FileInputStream fis;
ObjectInputStream ois;
try {
fis = new FileInputStream(new File(file, filename));
ois = new ObjectInputStream(fis);
note = (Note) ois.readObject();
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
return note;
}
I've also tried with this and nothing
String file = context.getCacheDir() + File.separator + "SubDir";
I don't see anywhere in the code you posted where you actually create the sub-directory. Here's some example code to save a file in a sub-directory, by calling mkdirs if the path doesn't yet exist (some parts here need to be wrapped in an appropriate try-catch for an IOException, but this should get you started).
File cachePath = new File(context.getCacheDir(), "SubDir");
String filename = "test.jpeg";
boolean errs = false;
if( !cachePath.exists() ) {
// mkdir would work here too if your path is 1-deep or
// you know all the parent directories will always exist
errs = !cachePath.mkdirs();
}
if(!errs) {
FileOutputStream fout = new FileOutputStream(cachePath + "/" + filename);
fout.write(bytes.toByteArray());
fout.flush();
fout.close();
}
You need to make your directory with mkdir.
In your code:
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
file.mkdir();
File file2 = new File(file, each_filename);
I am creating a dat file in C: drive folder named abc as shown below , Now my file is generated everyday
now suppose if my file is generated today, then tommrow it will be also generated as usual
but when tommrow it is generated I have to make sure that earlier day file is deleted as the space in that folder is limited and this check is every time need to be done previos day file to be get deleted from that folder , please advise how to achieve this..
File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc //and filename through a method
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(
file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
fileOutput));
why not use file.delete() ?
File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc //and filename through a method
if (file.exists()) {
file.delete(); //you might want to check if delete was successfull
}
file.createNewFile();
FileOutputStream fileOutput = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutput));
If your file name same in time to time no need to delete that. By running your code tomorrow, will over write file created today.
Consider following case
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\Test\test.txt"));
bw.write("abbbb");
bw.close(); // now this will create a test.txt in side Test folder
now run this by change writing String
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\test.txt"));
bw.write("hihi");
bw.close(); // now you can see file only containing hihi
You can change your code this way:
if (file.exists()) {
file.delete();
}
file.createNewFile();
And if it does not work, it's a matter of permission.
If you are using Java 7 then there is standard way to get file creation time, So that you can check if file is created in previous day and should be delete.
Path path = Paths.get("/filepath/");
BasicFileAttributes fileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("creationTime:"+ fileAttributes.creationTime());
I am working on a log file that is currently over-writing itself every single time. Now The thing is all i want it to do is to just write on the first line and append the list below to show the history from newest to oldest. Problem is I am not sure how to go about it I am looking at the code but don't know what I am doing wrong. Here is the code not sure if I am missing something or not.
String historylog = new Date().toString();
BufferedWriter bw = null;
String filepath = "C:\netbeans\Source code\test3";
String filename = "PatchHistory.log";
try
{
if (!(new File( filepath).exists()))
(new File( filepath)).mkdirs();
bw = new BufferedWriter( new FileWriter( filepath + File.separator
+ filename, true));
bw.write( historylog + "\r\n");
bw.newLine();
bw.flush();
bw.close();
return true;
}
catch (IOException){
return false;
}
Any Help would be appreciated not sure what I am doing wrong with this.
If I have understood you, you want to add log entries at the beginning of a log file.
AFAIK, (if you know any exceptions please tell me) all filesystems add data to the end of file. And Direct Access would overwrite the beginning of the file.
Your best option would be writting the log to a different file and, after writting what you want, write after that the contents of the original log file. Once done, close both files and overwrite the old file with the new one.
In your code
You are wrong here, you didn't used if statement properly.
if (!(new File( filepath).exists()))
(new File( filepath)).mkdirs(); // file path not exist, then it will execute
bw = new BufferedWriter( new FileWriter( filepath + File.separator + filename, true)); // this append file will always execute
Solution
if (!(f.exists())) {
//create new file
bw = new BufferedWriter(new FileWriter(filepath + File.separator + filename, false));
}
else{
//append in existing file
bw = new BufferedWriter(new FileWriter(filepath + File.separator + filename,true));
}
Basically i have two questions. i am using the below code to read and write z text file.
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("my text here");
myOutWriter.close();
this create a new file every time i want this to OPEN_OR_CREATE(if file already exist don't create a new one)
Ad my second question is that how to change the path "/sdcard/mysdfile.txt" i want this file to stored in my sdcard -> subFolder1 -> SubFolder2
Thnaks
Do not use hardcoded /sdcard or /mnt/sdcard or your app will fail as devices vary on location or mountpoint of that storage. To get the right location use
Environment.getExternalStorageDirectory();
See docs here.
To append content to existing file use new FileOutputStream(myFile, true); instead of just new FileOutputStream(myFile); - see docs on that constructor here.
As for
how to change the path "/sdcard/mysdfile.txt"
Aside from getting rid of /sdcard as said above, just add subfolders to the paths: MyFolder1/MyFolder2/mysdfile.txt. Note these folder have to exists or the path will be invalid. You can always create it by calling myFile.mkdirs().
Replace
FileOutputStream fOut = new FileOutputStream(myFile);
with
FileOutputStream fOut = new FileOutputStream(myFile, true); //true means append mode.
Appart from that I have one suggestion for you.
Never never hardcode /sdcard in code,Rather consider writing.
File myFile = new File(Environment.getExternalStorageDirectory(),"mysdfile.txt");
Try my solution to write to end of text file
private void writeFile (String str){
try {
File f = new File(Environment.getExternalStorageDirectory().toString(),"tasklist.txt");
FileWriter fw = new FileWriter(f, true);
fw.write(str+"\n");
fw.flush();
fw.close();
} catch (Exception e) {
}
}
*File(Environment.getExternalStorageDirectory().toString()+"your/pth/here","tasklist.txt");
File dir = Environment.getExternalStorageDirectory();
File f = new File(dir+"/subFolder1/",xyz.txt); <-- HOW TO USE SUB FOLDER
if(file.exists())
{
// code to APPEND
}
else
{
// code to write new one
}
1> OPEN_OR_CREATE
You can try or can replace MODE_APPEND with true like #Vipul's suggestion
FileOutputStream fOut = openFileOutput(your_path_file, MODE_APPEND);
//it means if the file is exist the content you want write will append into it.
2> stored in my sdcard -> subFolder1 -> SubFolder2
you can use Environment.getExternalStorageDirectory().getAbsolutePath() to get full file path the SDCard. Then concat strings to get the file path you want. Ex:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
File f = new File(baseDir + File.separator + subfolder1 + File.separator + subfoler2, fileName);
In Java 7 we can do it this way:
Path path = Paths.get("/sdcard/mysdfile.txt");
BufferedWriter wrt = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND);