Error while creating directory to store file - java

I need help to store new folders created according to the current time. After adding the codes for the time, I have received error stating that the system cannot find the path specified.
Here's my current code:
public void fileCreation( String fileData ) throws IOException
{
String nameOfFile = "c:\\Shane\\Work\\Desktop\\Storage_" + Config.retrieveDate + "\\" + this.nameOfFile + ".csv";
FileWriter writeFile = new FileWriter (nameofFile);
writeFile.append( fileData );
writeFile.flush();
writeFile.close();
}
My Config file has the current line of code:
public static String retrieveDate = "";
And declaration at another file:
Config.retrieveDate = sdf.format(new Date());
Output should be: e.g. ( Storage_20150416082500 ) -YYYYMMDDHHMMSS format.
Edit
Error occured:
java.io.FileNotFoundException: c:\Shane\Work\Desktop\Storage_2015041061404210\Type A.csv (Access is denied)
at test.DataGetter.fileCreation(Retrieval.java:55)

It looks like the directory c:\Shane\Work\Desktop\Storage_20150416082500 doesn't exist when you first try to create a file to it.
If that's the case, you should first check if the directory exists and if not, create it. Only then can you create a file within it:
public void fileCreation(String fileData ) throws IOException {
String dirName = "c:\\Shane\\Work\\Desktop\\Storage_" + Config.retrieveDate + "\\";
File dir = new File(dirName);
if (!dir.exists())
dir.mkdir();
//directory definitely exists here, we can create a file to it:
String nameOfFile = dirName + this.nameOfFile + ".csv";
FileWriter writeFile = new FileWriter (nameofFile);
writeFile.append( fileData );
writeFile.flush();
writeFile.close();
}
Of course for that to work, the parent directory (c:\Shane\Work\Desktop) would have to exist in the first place.

If you are going to access an existing file its a good practice to always Try checking if the file really exist or not , you can achieve it by
File file=new File(pathToYourFile.extension);
if(file.exists()){
// do whatever you want to do
}
else{
//either throw any exception or create that file manually if required
}

Make sure the directories you are trying to create the file in are present, if not present, create.
public void fileCreation( String fileData ) throws IOException {
String nameOfFile = "c:\\Shane\\Work\\Desktop\\Storage_" + Config.retrieveDate + "\\" + this.nameOfFile + ".csv";
// Make directories if not present
new File(nameOfFile).getParentFile().mkdirs();
FileWriter writeFile = new FileWriter (nameofFile);
writeFile.append( fileData );
writeFile.flush();
writeFile.close();
}

Related

Cannot create file with Java using the Parent and Child parameters of the new File constructor

I am trying to create a file using Java. I want to create this file in a sub-folder of my "Documents" directory. I want this sub-folder to be based today's date.
I thought I new how to use the File class and file.mkdirs() method properly, but I guess I don't.
Here is what I have:
public class FileTest {
private static final String sdfTimestampFormat = "yyyy-MM-dd HH:mm:ss Z";
private static final SimpleDateFormat timestampSDF = new SimpleDateFormat(sdfTimestampFormat);
private static final String sdfDirFormat = "yyyy-MM-dd";
private static final SimpleDateFormat dirSDF = new SimpleDateFormat(sdfDirFormat);
public static void test() throws FileNotFoundException, IOException{
Date rightNow = new Date();
String data = "the quick brown fox jumps over the lazy dog";
String path = System.getProperty("user.home");
String filename = "file.txt";
String directory_name = path + System.getProperty("file.separator") + "Documents" + System.getProperty("file.separator") + dirSDF.format(rightNow);
File file = new File(directory_name, filename);
if(file.mkdirs()){
String outstring = timestampSDF.format(rightNow) + " | " + data + System.getProperty("line.separator");
FileOutputStream fos = new FileOutputStream(file, true);
fos.write(outstring.getBytes());
fos.close();
}
}
}
What is happening is that the following directory is created:
C:\Users\<username>\Documents\2018-08-03\file.txt\
I was under the impression that the Parent parameter of the new File constructor was the base directory, and the Child paramater of the new File constructor was the file itself.
Is this not the case? Do I need two File objects, one for the base directory and another for the file?
What I want is this:
C:\Users\<username>\Documents\2018-08-03\file.txt
Thanks.
mkdirs() will do directories (if they don't exist) for each element in your path.
So you can use file.getParentFile().mkdirs() to not make a directory for your file.txt
Edit: Something to consider
mkdirs() only returns true if it actually created directories. If they already existed or there was a problem creating them it will return false
Since you are trying to run this multiple times to append to your text your logic will not run inside your if-statement
I would change it to:
boolean created = true;
if(!file.getParentFile().exists()) {
created = file.getParentFile().mkdirs();
}
if (created) {
String outstring = timestampSDF.format(rightNow) + " | " + data + System.getProperty("line.separator");
FileOutputStream fos = new FileOutputStream(file, true);
fos.write(outstring.getBytes());
fos.close();
}

Java get resource is not working

I try to read a resource file from my application but it doesn't work.
Code:
String filename = getClass().getClassLoader().getResource("test.xsd").getFile();
System.out.println(filename);
File file = new File(filename);
System.out.println(file.exists());
Output when I execute the jar-file:
file:/C:/Users/username/Repo/run/Application.jar!/test.xsd
false
It works when I run the application from IntelliJ but not when I execute the jar-file. If I open my jar-file with 7-zip test.xsd is located in the root-folder. Why isn't the code working when I execute the jar-file?
Also, File refers to actual OS file-system files; in the OS's file-system, there is only a jar file, and that jar file is not a folder. You should either extract the contents of the URL to a temporary file, or operate with its bytes in-memory or as a stream.
Note that myURL.getFile() is returning a String representation, and not an actual File. In a similar way, this will not work:
File f = new URL("http://www.example.com/docs/resource1.html").getFile();
f.exists(); // always false - will not be found in the local filesystem
A nice wrapper could be the following:
public static File openResourceAsTempFile(ClassLoader loader, String resourceName)
throws IOException {
Path tmpPath = Files.createTempFile(null, null);
try (InputStream is = loader.getResourceAsStream(resourceName)) {
Files.copy(is, tmpPath, StandardCopyOption.REPLACE_EXISTING);
return tmpPath.toFile();
} catch (Exception e) {
if (Files.exists(tmpPath)) Files.delete(tmpPath);
throw new IOException("Could not create temp file '" + tmpPath
+ "' for resource '" + resourceName + "': " + e, e);
}
}

Copy file1 name inplace of file2 and add extra to it, but not copy file1 extention

How can i change the name of a file to match the original file and have extra txt in it, please see example below
Original
dataFile.txt
thisNameNeedsToMatchDataFile.txt (but also have ".Step2" added in before the .txt)
Desired output
dataFile.txt
dataFile.Step2.txt
Any help would be appropriated thank you in advanced.
How i understand your problem this is how i think the solution could look like
(java 7+)
public class FileConverter {
public static void main(String[] args) throws IOException {
FileConverter converter = new FileConverter();
File newFile1 = new File("c:/parent1/file1.dump");
File newFile2 = new File("c:/parent2/file2.dump");
converter.convert2Files(newFile1, newFile2);
}
private void convert2Files(File file1, File file2) throws IOException {
// compare if the 2 files have the same name
if(file1.getName().equalsIgnoreCase(file2.getName())){
String newName = file1.getName().substring(0, file1.getName().lastIndexOf('.'));
String newNameOriginal = newName + ".txt";
String newNameStep2 = newName + ".Step2.txt";
File newFileOriginal = new File(file1.getParent(),newNameOriginal);
File newFileStep2 = new File(file1.getParent(),newNameStep2);
Path file = file1.toPath();/* use file1 as source file */
Path to = Paths.get(file1.getParent());/* path to destination directory */
Files.copy(file, to.resolve(newFileOriginal.toPath()));
Files.copy(file, to.resolve(newFileStep2.toPath()));
}
}
}

Write String to multiple txt files

The following code writes a string to a specific file.
String content = "Text To be written on a File";
File file = new File("c:/file.txt");
FileOutputStream foutput = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
byte[] c = content.getBytes();
foutput.write(c);
foutput.flush();
foutput.close();
I want to use this code in a Jbutton so every time the user clicks it, it writes the string to a NEW text file NOT OVERWRITE the existed one. I tried to do but I couldn't get the result.
Thank you in advance.
There's a couple of different ways you can get this result, it really depends on the application. The two easiest ways to do this would to be either:
Append the current timestamp to the file name
Use the File API to create a "temp file" in the directory, which is guarenteed to have a unique name
Option 1:
String baseDir = "c:/";
File newFile = new File(baseDir, "file_" + System.currentTimeMillis() + ".txt");
// do file IO logic here...
Option 2:
String baseDir = "c:/";
File newFile = File.createTempFile("file", ".txt", new File(baseDir));
// do file IO logic here...
If you want to write it to a new file, you have to create a new file. The name of the text file is always file.txt in your case.
Try this:
private int filecounter = 0; // this is the member of your class. Outside the function.
//inside your function
File file = new File("c:/file" + Integer.(filecounter).toString() + ".txt");
// you do something here.
filecounter++;
This way, your files will be stored as file0.txt, file1.txt etc.

Weird exception in thread "main" java.io.FileNotFoundException I/O Java

I have this error when I am trying to read the file:
Exception in thread "main" java.io.FileNotFoundException: \src\product.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at dao.Inventory.readFile(Inventory.java:30)
at view.InventoryView.init(InventoryView.java:33)
at view.InventoryView.<init>(InventoryView.java:21)
at view.InventoryView.main(InventoryView.java:211)
But the thing is, I have the product.txt in my src folder.
My code is the following:
public void readFile() throws IOException {
// input file must be supplied in the first argument
InputStream istream;
File inputFile = new File("\\src\\product.txt");
istream = new FileInputStream(inputFile);
BufferedReader lineReader;
lineReader = new BufferedReader(new InputStreamReader(istream));
String line;
while ((line = lineReader.readLine()) != null) {
StringTokenizer tokens = new StringTokenizer(line, "\t");
// String tmp = tokens.nextToken();
// System.out.println("token " + tmp);
ActionProduct p = new ActionProduct();
prodlist.add(p);
String category = p.getCategory();
category = tokens.nextToken();
System.out.println("got category " +category);
int item = p.getItem();
item = Integer.parseInt(tokens.nextToken());
String name = p.getName();
System.out.println("got name " +name);
double price = p.getPrice();
price = Double.parseDouble(tokens.nextToken());
int units = p.getUnits();
units = Integer.parseInt(tokens.nextToken());
}
}
I don't think anything is wrong with my code. Also, I saw a similar post about a hidden extension like FILE.TXT.TXT, how would you show a hidden extension in MacOSX?? Any suggestions? (Would there be any other problem besides the hidden extension issue?)
/src/product.txt is an absolute path, so the program will try to find the file in the src folder of your root path (/). Use src/product.txt so the program will use this as a relative path.
It's possible (most likely?) that your Java code is not executing inside the parent folder of src, but instead inside a 'class' or a 'bin' folder with the compiled java .class files.
Assuming that 'src' and 'bin' are in the same directory, you could try ..\\src\\product.txt
See also http://en.wikipedia.org/wiki/Path_(computing)
As other commenters stated, the path is absolute and points to
\src\product.txt which is (hopefully) not where
your sources are stored.
The path separator should be set in an OS-independent manner using
the System.getProperty("path.separator") property. On a Unix system, you'll have trouble with hard coded backslashes as path separators. Keep it portable!
String pathSeparator = System.getProperty("path.separator");
String filePath = "." + pathSeparator + "src" + pathSeparator + "product.txt";
File file = new File(filePath);
or better yet:
// this could reside in a non-instantiable helper class somewhere in your project
public static String getRelativePath(String... pathElements) {
StringBuilder builder = new StringBuilder(".");
for (String pathElement : pathElements) {
builder.append(System.getProperty("path.separator");
builder.append(pathElement);
}
return builder.toString();
}
// this is where your code needs a path
...
new File(getRelativePath("src", "product.txt");
...

Categories

Resources