Here is my class, what I am doing wrong. Why is my text document becoming a file folder. Please explain what is going on and how I can correct it. Thank you
public class InputOutput {
public static void main(String[] args) {
File file = new File("C:/Users/CrypticDev/Desktop/File/Text.txt");
Scanner input = null;
if (file.exists()) {
try {
PrintWriter pw = new PrintWriter(file);
pw.println("Some data that we have stored");
pw.println("Another data that we stored");
pw.close();
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
}
} else {
file.mkdirs();
}
try {
input = new Scanner(file);
while(input.hasNext()) {
System.out.println(input.nextLine());
}
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
} finally {
if (input != null) {
input.close();
}
}
System.out.println(file.exists());
System.out.println(file.length());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.isFile());
System.out.println(file.isDirectory());
}
}
Thanks. The above is my Java class.
You mistakingly assume Text.txt is not a directory name.
mkdirs() creates a directory (and all directories needed to create it). In your case 'Text.txt'
See here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#mkdirs().
It is perfectly fine for a directory to have a . in it.
You could use getParentFile() to get the directory you want to create and use mkdirs() on that.
For additional informations. Here is the différence between the two representaions of files and directories:
final File file1 = new File("H:/Test/Text.txt"); // Creates NO File/Directory
file1.mkdirs(); // Creates directory named "Text.txt" and its parent directory "H:/Test" if it doesn't exist (may fail regarding to permissions on folders).
final File file = new File("H:/Test2/Text.txt"); // Creates NO File/Directory
try {
file.createNewFile(); // Creates file named "Text.txt" (if doesn't exist) in the folder "H:/Test2". If parents don't exist, no file is created.
} catch (IOException e) {
e.printStackTrace();
}
Replace your code:
else {
file.mkdirs();
}
with:
else {
if (!file.isFile()&&file.getParentFile().mkdirs()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
This question already has answers here:
Java 'file.delete()' Is not Deleting Specified File
(8 answers)
Closed 5 years ago.
Here is my code of deleting the pdf file
try {
File file = new File(docObjectId + ".pdf");
file.setWritable(true);
System.out.println(file.length());
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
It goes to the else part of the code.
PDF file is in project root folder and I am able to delete it manually. Scratching my head now.
Here is complete method. It might be due to some other reason
public Response getContractDocument(#PathParam("docid") String docObjectId) throws Exception {
DocumentumService documentumService = new DocumentumService(documentumConfigUtil);
DocumentumDocumentBean docDocumentBean = documentumService.getContractDocContent(docObjectId, true);
FileInputStream fileInputStream;
fileInputStream = new FileInputStream(docDocumentBean.getDocFile());
compressPdf(fileInputStream,docObjectId + ".pdf");
fileInputStream = new FileInputStream(docObjectId + ".pdf");
ResponseBuilder responseBuilder = Response.ok((Object) fileInputStream);
try {
File file = new File(docObjectId + ".pdf");
System.out.println(file.getAbsolutePath());
file.setWritable(true);
System.out.println(file.length());
File d = new File(file.getAbsolutePath());
if (d.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch(Exception e) {
e.printStackTrace();
}
return responseBuilder.build();
}
My experience is with windows. The reason that a file won't delete is always the same. Some object has a connection to the file and is holding it open. In this case, it looks like it might be fileInputStream.
Try this before you attempt to delete:
fileInputStream.close();
Change if(file.delete) to
try {
file.delete();
System.out.println("file deleted");
} catch(IOException e) {
System.out.println("file not deleted");
}
The exception may not be accurate.
First, check if the file exist or not and then delete it.
Kindly use the below code. Its working fine and is very clear approach for deletion. I hope it would help.
public static void main(String[] args) {
try{
File file = new File("C:/Users/Tehmina Yaseen/Documents/NetBeansProjects/FileDeletion/src/filedeletion/Myfile.pdf");
if (file.exists()) {
file.delete();
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the output:
I have a program where it searches for a file(it already has some content in it) based on the given directory path and lets the user add more content to that file. I was able to show all the files on the directory, but I am not sure how to select a file and write more content to it. Here is my code so far:
public static void main(String [] args)
{
// This shows all the files on the directory path
File dir = new File("/Users/NasimAhmed/Desktop/");
String[] children = dir.list();
if (children == null)
{
System.out.println("does not exist or is not a directory");
}
else
{
for (int i = 0; i < children.length; i++)
{
String filename = children[i];
System.out.println(filename);
// write content to sample.txt that is in the directory
out(dir, "sample.txt");
}
}
}
public static void out(File dir, String fileName)
{
FileWriter writer;
try
{
writer = new FileWriter(fileName);
writer.write("Hello");
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
Example append to file:
public static void appendToFile(File dir, String fileName) {
try (FileWriter writer = new FileWriter(new File(dir, fileName), true)) {
writer.write("Hello");
} catch(IOException e) {
e.printStackTrace();
}
}
// write content to sample.txt that is in the directory
try {
Files.write(Paths.get("/Users/NasimAhmed/Desktop/" + filename), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Used - How to append text to an existing file in Java
I want to create a file if and only if that file does not exist.
As an example file location is referring to "C:\user\Desktop\dir1\dir2\filename.txt"
if (!file.exists()) {
try {
file.createNewFile();
} catch(IOException ioe) {
ioe.printStackTrace();
return;
}
}
Unfortunately the above code is failing, as the dir1 and dir2 does not exist.
For my case
Sometime the dir1 and dir2 may exist and sometime they may not exist.
I do not want to overwrite the contents of these intermediate directories if they already exists,
How to check this cleanly?
I was thinking to add the following check to handle this condition:
if (!file.getParentFile().getParentFile().exists()) {
file.getParentFile().getParentFile().mkdirs();
}
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch(IOException ioe) {
ioe.printStackTrace();
return;
}
}
Or there is a clearer solution than this?
you can do something of this sort:
file.getParentFile().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.
Update
if (file.getParentFile().exists || file.getParentFile().mkdirs()){
try
{
file.createNewFile();
}
catch(IOException ioe)
{
ioe.printStackTrace();
return;
}
} else {
/** could not create directory and|or all|some nonexistent parent directories **/
}
Beware that File.exists() checks for the existence of a file or directory.
Instead of:
if(!file.exists()) {
try {
file.createNewFile();
} catch(IOException ioe) {
ioe.printStackTrace();
return;
}
}
You should explicitly check if the file is a file as there may be a directory of the same name:
if(!file.isFile()) {
try {
file.createNewFile();
} catch(IOException ioe) {
ioe.printStackTrace();
return;
}
}
Similarly, you should check that the parent file is a directory:
if (!file.getParentFile().getParentFile().isDirectory()) { ... }
I am creating a properties file and putting into my classpath folder Resources.
When I tried to read this file , i am not getting the expected result. i am getting the result of the previous values printed instead of the property values set now.
My class file is as follows :
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
PrintWriter output = null;
try {
output = new PrintWriter("Resources/config.properties");
// set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "mkyong");
prop.setProperty("dbpassword", "password");
// save properties to project root folder
prop.store(output, null);
if(output!=null) {
System.out.println("Output");
output.close();
}
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
output.close();
}
}
Properties prop1 = new Properties();
BufferedInputStream input = null;
try {
String filename = "config.properties";
input = (BufferedInputStream) AppCPLoad.class.getClassLoader().getResourceAsStream(filename);
if(input==null){
System.out.println("Sorry, unable to find " + filename);
return;
}
//load a properties file from class path, inside static method
prop1.load(input);
//get the property value and print it out
System.out.println(prop1.getProperty("database"));
System.out.println(prop1.getProperty("dbuser"));
System.out.println(prop1.getProperty("dbpassword"));
if(input!=null) {
System.out.println("Input");
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally{
if(input!=null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Please help.
When you run the program, the properties file is loaded and the values are read. After you rewrite the properties file, that doesn't mean that the properties you have loaded already have be to rewritten. You need to reload the properties file and re-read the values. You are looking for an implementation like ReloadableResourceBundleMessageSource
Try to create file in specific directory but it shows the error FileNotFound. Why?
Am I using impossible path? I really don't know, but is seems like the code should be working.
String day=/1;
String zn="/zn";
File_name=zn
String root= Environment.getExternalStorageDirectory().toString();
File_path=root+day;
File file1 = new File(File_path,File_name);
file1.mkdirs();
if(!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream fos= new FileOutputStream(file1);
String l,d,p;
l = lessnum.getText().toString();
d = desc.getText().toString();
p = place.getText().toString();
fos.write(l.getBytes());
fos.write(d.getBytes());
fos.write(p.getBytes());
fos.close();
Change your code as for creating a file on sdcard
String root= Environment.getExternalStorageDirectory().getAbsolutePath();
String File_name = "File_name.Any_file_Extension(like txt,png etc)";
File file1 = new File(root+ File.separator + File_name);
if(!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
In current you you are also missing file Extension with file name so change String zn as zn="/zn.txt";
and make sure you have added Sd card permission in AndroidManifest.xml :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
First you make a directory
String root= Environment.getExternalStorageDirectory().toString();
String dirName =
root+ "abc/123/xy";
File newFile = new File(dirName);
newFile.mkdirs();
then you create a file inside that directory
String testFile = "test.txt";
File file1 = new File(dirName,testFile);
if(!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
then do your file writing operations
try { OutputStream fos= new FileOutputStream(file1);
String l,d,p;
l = lessnum.getText().toString();
d = desc.getText().toString();
p = place.getText().toString();
os.write(l.getBytes());
fos.write(d.getBytes());
fos.write(p.getBytes());
fos.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think this will help you...
Thanks...
you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And check http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29
String root= Environment.getExternalStorageDirectory().toString();
String dirName =
root+ "abc/123/xy";
File newFile = new File(dirName);
newFile.mkdirs();
String testFile = "test.txt";
File file1 = new File(dirName,testFile);
if(!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And and <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
on manifest file...
Thanks...
Here is your latest attempt:
File_path = root + File.separator + day;
File f_dir = new File(File_path);
f_dir.mkdirs();
File file1 = new File(f_dir, File_name);
if (!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream fos= new FileOutputStream(file1);
If you showed us the complete stacktrace and error message it would be easier to figure out what is going wrong, but I can think of a couple of possibilities:
You are not checking the value returned by f_dir.mkdirs(), and it could well be returning false to indicate that the directory path was not created. This could mean that:
The directory already existed.
Something existed but it wasn't a directory.
Some part of the directory path could not be created ... for one of a number of possible reasons.
The file1.exists() call will return true if anything exists with that pathname given by the object. The fact that something exists doesn't necessarily mean that you can open it for writing:
It could be a directory.
It could be a file that the application doesn't have write permissions for.
It could be a file on a read-only file system.
And a few other things.
If I was writing this, I'd write it something like this:
File dir = new File(new File(root), day);
if (!dir.exists()) {
if (!dir.mkdirs()) {
System.err.println("Cannot create directories");
return;
}
}
File file1 = new File(dir, fileName);
try (OutputStream fos= new FileOutputStream(file1)) {
...
} catch (FileNotFoundException ex) {
System.err.println("Cannot open file: " + ex.getMessage());
}
I only attempt to create the directory if required ... and check that the creation succeeded.
Then I simply attempt to open the file to write to it. If the file doesn't exist it will be created. If it cannot be created, then the FileNotFoundException message should explain why.
Notice that I've also corrected the style errors you made in your choice of variable names.