Why does File related stuff not Work? (Java) - java

Im currently writing a program which involves creating a Folder and a File within this Folder.
The first version worked, after that i decided to create a new project to give the code a clear form.
Now, suddenly the class creating the Files wont work anymore. I switched devices with the second project.
package com.company;
import java.io.*;
public class File {
File folder1 = new File("Data");
File file1 = new File("Data/MonData.txt");
//For both "Data" and "Data/MonData.txt it says
//"Expected 0 arguments but found 1"
public void DataText() {
if(folder1.exists()) { //exists = cant
} //resolve method
else {
folder1.mkdirs(); //mkdirs = cant
} //resolve method
if(file1.exists()) { //exists = cant
} //resolve method
else {
try {
file1.createNewFile(); //createNewFile = cant
} //resolve method
catch(IOException e) {
e.printStackTrace();
}
}
}
}

You should name your class in a different way. Naming your class File let java use it instead of java.io.File, so the method exists (and so the others) is not found because not in your class.

Your class name & importing class has same name File, So compiler check for your File class not java.io.File one which he should.
In case two class had same name, use java.io.File & your.File instead of File only

Both the classes of yours have the same name. Try naming the class File to java.io.File .
It should work fine

You can use fully qualified name
java.io.File folder1 = new java.io.File("Data");
java.io.File file1 = new java.io.File("Data/MonData.txt");

Related

Java : how to create a directory inside under usr in linux from a java app?

I'm trying to create a folder under /usr in linux from a java program. Here's what I've done. I understand that I lack the permission to do so under /usr but what do I need to add?
public void createDirectory (String path)
{
File directory = new File(path);
if (!directory.exists()) {
if (!directory.mkdirs()) {
System.out.println("couldn't create file");
}
}
}
Here the sysout statement gets printed. what needs to be done here? Would greatly appreciate your help and thanks in advance.
mkdirs() is used in case you want to create nested folders.
Try with mkdir() instead:
public void createDirectory (String path)
{
File directory = new File(path);
if (!directory.exists()) {
if (!directory.mkdir()) {
System.out.println("couldn't create file");
}
}
}
Please note that you must provide the full path in order to make it work. Also as #Reimeus mentioned in the comment above, is not a good idea to write or create anything at that level, I would suggest to create it under /home/your_user/

How to remove garbage value from a file name which has been created by using createTempFile() method

I have used File.createTempFile() method to create temp file but as its output it appends the garbage value with the file name too. I used the method for uploading zipfile, but unable to delete those appended garbage value. For further functionality I need the exact name of file.
Kindly help...
Highly appreciate your response.
My concern is, as code stated by niiraj874u, I am getting the the File name : tmp4501156806082176909.txt
But I want only tmp.txt How can I remove appended numeric value?
You can use java.io.File.getName() method to get name of file..
import java.io.File;
import java.io.IOException;
public class FileDemo {
public static void main(String[] args) {
File f = null;
// creates temporary file
try {
f = File.createTempFile("tmp", ".txt", new File("D:/"));
} catch (IOException e) {
e.printStackTrace();
}
// prints name of temp file
System.out.println("File name: "+f.getName());
// prints absolute path
System.out.println("File path: "+f.getAbsolutePath());
}
}
this will print like
File name: tmp4501156806082176909.txt
File path: D:\tmp4501156806082176909.txt
It sounds like you don't need a temp file. The purpose of the "garbage" is to protect two or more instances of the app from overwriting each other. In this case use system.getProperty("java.io.temp") to get the temp dir.

What is the simplest way to create a file?

This doesn't seem to create a file or folder. Why?
import java.io.*;
public class file1
{
public static void main(String[] args)
{
File text1 = new File("C:/text1.txt");
File dir1 = new File("C:/dir");
}
This one below does create a file.
import java.io.*;
public class file3
{
public static void main(String[] args)
{
try
{
FileWriter text1 = new FileWriter("C:/text.txt");
FileWriter dir = new FileWriter("C:/dir");
}
catch(Exception e){}
}
}
However, the directory seems to have a strange unusable icon.
What can I do to create a directory.
What are other simple methods to create files and folders.
Surprisingly, the File class does not represent a file. It actually represents a pathname for a file ... that may or may not exist.
To create a file in Java, you need to open it for output; e.g.
File text1 = new File("C:/text1.txt");
FileOutputStream os = new FileOutputStream(text1); // The file is created
// here ... if it doesn't
// exist already.
// then write to the file and close it.
or you could do this - new FileOutputStream("C:/text1.txt"). In both cases, an existing file will be truncated ... unless you use the FileOutputStream with a boolean parameter that says open for appending.
If you want to create a file without writing any data to it, you could also do this:
File text1 = new File("C:/text1.txt");
text1.createNewFile();
However, that will only create a new file if the file didn't already exist.
To create a directory in Java, use the File.mkdir() or File.mkdirs() methods.
UPDATE
You commented:
I tried File dir = new File("C:/dir1").mkdir(); it says incompatible types.
That is right. The mkdir() method returns a boolean to say whether or not it created the directory. What you need to write is something like this:
File dir = new File("C:/dir1");
if (dir.mkdir()) {
System.out.println("I created it");
}
Always READ THE JAVADOCS before using a method or class you are not familiar with!
A couple more things you need to know:
The best way to deal with the problem of making sure a file gets closed is to do something like this:
try (FileOutputStream os = new FileOutputStream(text1)) {
// now write to it
}
The stream os will be closed automatically when the block exits.
It is usually "bad practice" to catch Exception. It is always "bad practice" to catch Exception and do nothing in the handler. This kind of this hides the evidence of bugs, and makes your code unpredictable and hard to debug.
If you're creating a directory with File, you want this:
new File("C:/dir").mkdirs();
For creating directory you can use :
if(!text1.exists()){
text1.mkdir();
}
and for creating file use:
if(!text1.exists()){
try {
text1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}

Writable file permission problems

In a project I'm working on in Windows 7, using JDK 7u25, I have a class that stores the state for the application. That class has a static save method to save the state to disk. I originally had the following code. (state is a JSONObject and I'm assuming that the output directory hasn't necessarily been created when this function is called.)
public State {
private static String stateFile = "\\state\\state.json";
public static void save() {
try {
File sFile = new File(stateFile);
sFile.mkdirs();
sFile.setWritable(true);
FileWriter file = new FileWriter(sFile);
String str = state.toString(4);
file.write(str);
file.close();
} catch (IOException ex) {
HLogger.log(ex.getMessage());
}
}
}
Whenever I ran this code, it logged an IOException - complaining that access to the state file was denied. I discovered that if I changed the save function (as shown below) it would work exactly as expected.
public static void save() {
try {
File sFile = new File(stateFile);
File path = new File(sFile.getParent());
path.mkdirs();
sFile.setWritable(true);
FileWriter file = new FileWriter(sFile);
String str = state.toString(4);
file.write(str);
file.close();
} catch (IOException ex) {
HLogger.log(ex.getMessage());
}
}
Can anyone explain why it's necessary to create the output directory in a separate file object in order to obtain write permission for the file?
This is not permissions failure but is a misuse of FileWriter.
In the first code snippet a directory named state.json is being created by the call to mkdirs() because it:
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.
and then an attempt to write to the directory using a FileWriter is made, which fails. The following is the throws clause From FileWriter(File):
IOException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
The second snippet creates a directory named state (because it is using the parent of \\state\\state.json) and then a file named state.json, and therefore uses FileWriter on a regular file which succeeds.

Java formatter - setting file directory

i am trying to create a text file in a folder (called AMCData). The file is called "File" (for the sake of this example).
I have tried using this code:
public static void OpenFile(String filename)
{
try
{
f = new Formatter("AMCData/" + filename + ".txt");
}
catch(Exception e)
{
System.out.println("error present");
}
}
But before i get the chance to even place any text in it, the catch keeps being triggered..
Could anyone inform me why this is occuring?
more information:
The folder does not exist, i was hoping it would automatically create it
If it doesn't automatically create folders, could you please link me to how to do so?
You're right, a Formatter(String) constructor needs the file to be present or createable. The most likely reason why a file cannot be created is that it references a folder that itself doesn't exist, so you should use the File.mkdirs() method, like this:
new File("AMCData").mkdirs();

Categories

Resources