NIO getParentFile().mkdir() [duplicate] - java

This question already has answers here:
Using Java nio to create a subdirectory and file
(3 answers)
Closed 8 years ago.
Is there a way to create a file and directory in one shot
as in below... (Using Java 7 and NIO... Paths and Files static methods ).
where you wouldn't have to type the Path and then file in separate lines ( of code ) ?
File file = new File("Library\\test.txt");
if (file.getParentFile().mkdir()) {
file.createNewFile();
} else {
throw new IOException("Failed to create directory " + file.getParent());
}
Basically looking for the equivalent approach to "getParentFile().mkdir()" off the Path ( and file ) entered in Java 7 NIO.
Thx

Actually realized it's accopmplished this way..
Path file = Paths.get("/Users/jokrasa/Documents/workspace_traffic/javaReviewFeb28/src/TEST/","testy.txt");
try {
Files.createDirectory(file.getParent());
Files.createFile(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So you don't have to type it in twice actually...
Cheers !

Related

How to append to existing file [duplicate]

This question already has answers here:
How to write data with FileOutputStream without losing old data?
(2 answers)
Closed 4 years ago.
I am trying to redirect the console input to a file. Problem is that every time i create a file it overwrites it or creates new files if I select the name of file to include unix timestamp. I saw similar questions here but I am not sure which approach or class to use.
PrintStream out;
PrintStream oldout = new PrintStream(System.out);
try {
out = new PrintStream(
new FileOutputStream(
workFolder + File.separator + "output" + Instant.now().getEpochSecond() + ".txt"));
System.setOut(out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.setOut(oldout);
So if there isn't a file to create it, but if there is already a file to just append new data, but not overwrite or create new files.
As per Java docs
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException
Parameters: name - the system-dependent file name
append - if true,
then bytes will be written to the end of the file rather than the
beginning
There is a constructor which allows passing the boolean value which decides whether to append the data in file or not.
You can use it.

a file addition by an incomplete (file) name [duplicate]

This question already has answers here:
How to check a file if exists with wildcard in Java?
(7 answers)
Closed 6 years ago.
I have a method:
public void setup () {
File file = new File(74761_control_*.xml)
//some code
}
Where * - variable part. Not known in advance how it will exactly be called a file. The program is required to load an xml file with the same name. Is there an elegant way to do this with a standard Java SE API?
The java.nio package has some convencience methods to iterate over directories using a file name pattern:
Path dir = Paths.get("c:\\temp");
Iterator<Path> iterator = Files.newDirectoryStream(dir,
"74761_control_*.xml").iterator();
Now, iterator "holds" all paths that fit to the glob pattern above.
The rest is iterator/file handling:
if (!iterator.hasNext()) {
// file not found
} else {
Path path = iterator.next();
// process file, e.g. read all data
Files.readAllBytes(path);
// or open a reader
try (BufferedReader reader = Files.newBufferedReader(path)) {
// process reader
}
if (iterator.hasNext()) {
// more than one file found
}
}

Files.newDirectoryStream(path) does not return files recursively [duplicate]

This question already has answers here:
Recursively list all files within a directory using nio.file.DirectoryStream;
(9 answers)
Closed 6 years ago.
I m expecting to see a list of all files located under path d:/test folder. However, I can only get the files directly under that folder, but not recursively.
Code:
String folder = "D:/test";
Path path = fs.getPath(folder);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)) {
for (Path p : directoryStream) {
System.out.println(p.getFileName());
}
} catch (IOException e) {
e.printStackTrace();
}
result:
a.txt
folder
folder structure:
Another way to this extending your own logic :
public static void printFileNamesRecursively(String path){
Path yourPath = FileSystems.getDefault().getPath(path);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(yourPath)) {
for (Path p : directoryStream) {
System.out.println(p.getFileName());
if(p.toFile().isDirectory()){
printFileNamesRecursively(p.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
The Files::newDirectoryStream are meant to behave like that. If you want to recursively retrieve all directories and files in the given directory and its sub-directories, you will need Files::walk or Files::walkFileTree. For example (I assume you use Java 8):
Path path = //...
try {
Files.walk(path).map(Path::getFileName).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
This is the right behavior for DirectoryStream. Instead, You can use org.apache.commons.io.FileUtils to enumerate the files recursively.

Java - How I can check if file is exist? [duplicate]

This question already has answers here:
How do I check if a file exists in Java?
(19 answers)
Closed 7 years ago.
I'm creating a file with writeToFile() function.
Before I call writeToFile() function, I want to check if the file already exist or not.
How can I do this?
code:
private void writeToFile(String data, String fileName) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.openFileOutput(fileName, Context.MODE_APPEND));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
You could utilize java.io.File and call the .exists() method to check if the file exists.
Use the following code to check if a file already exists.
if(file.exists() && !file.isDirectory()) {
// continue code
}
Using java.io.File
File f = new File(fileName);
if (f.exists()) {
// do something
}
This is a duplicate.
File file = new File("FileName");
if(file.exists()){
System.out.println("file is already there");
}else{
System.out.println("Not find file ");
}
The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists

Rename all files in a folder using java [duplicate]

This question already has answers here:
Rename a file using Java
(15 answers)
Closed 8 years ago.
How can we rename all files in a folder using java?
C:/temp/pictures/1.jpg
C:/temp/pictures/2.jpg
C:/temp/pictures/3.jpg
C:/temp/pictures/4.jpg
C:/temp/pictures/5.jpg
Rename to
C:/temp/pictures/landscape_1.jpg
C:/temp/pictures/landscape_2.jpg
C:/temp/pictures/landscape_3.jpg
C:/temp/pictures/landscape_4.jpg
C:/temp/pictures/landscape_5.jpg
Kind regards
Take a look at below code which check file in the folder and rename it.
File dir = new File("D:/xyz");
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles()) {
try {
File newfile =new File("newfile.txt");
if(f.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
I Hope It Will Help You

Categories