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
Related
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.
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 !
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
This question already has answers here:
Check if file is already open
(8 answers)
Closed 8 years ago.
All I need help with is testing whether the file is opened or not.
Here is what I have:
public static void main(String[] args) {
//Prompt user to input file name
SimpleIO.prompt("Enter File name: ");
String fileName = SimpleIO.readLine();
//Create file object
File file = new File (fileName);
//Check to see if file is opened
if (!file.exists()){
System.out.println("The file you entered either do not exist or the name is spelled wrong.\nProgram is now being terminated.\nGoodbye!");}
}
If this
//Create file object
File file = new File (fileName);
doesn't produce an exception, then the file was accessed correctly. However if you need to check if the file is being written to or if it's being otherwise accessed allready, you will need to check if it's locked.
File file = new File(fileName);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock = channel.lock();
try {
lock = channel.tryLock();
System.out.print("file is not locked");
} catch (OverlappingFileLockException e) {
System.out.print("file is locked");
} finally {
lock.release();
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to append text to an existing file in Java
I want to add data to a text file. So it's one after another...so something like:
1
2
3
<add more here>
But I don't want the text from the file to be deleted at all. This is the code i'm using atm, but it replaces what ever is in the file. Could someone please tell me how to do what I asked. Thanks.
FileWriter fstream = new FileWriter("thefile.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("blabla");
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
use this
FileWriter fstream = new FileWriter("thefile.txt",true);
the explanation
public FileWriter(String fileName, boolean append) throws IOException
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.