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();
Related
Im trying to write a function that will take a string, then open a file with that string name and read the text. I know how to do this, but im having trouble with the fact that my text files are not saved in the same place as my java file.
It looks like this.
Project name/src/program.java
Project name/resources/text.txt
Im using the File class, but dont know what to put in the File constructor to open to the right place.
ie. File store = new File(xxxxxxxxxtext.txt)
Help me out with what goes in front of the file name please. Also, this is java 6 and im on windows 8.
This is my code:
public static void areaSearch(String a) {
Scanner reader = null;
try {
reader = new Scanner(new File("../resources/" + a+ ".txt"));
}
catch (Exception e) {
System.out.println("File: " + a +" not opended...");
}
Use relative path if it's on an easy relative path from your project folder:
File file = File("../resources/text.txt");
Or use absolute path:
File file = File("C:\\abcfolder\\text.txt");
Read documentation. There are more, than 1 constructor for File class. Use:
public File(File parent, String child)
I don't understand how to use TextIO's readFile(String Filename)
Can someone please explain how can I read an external file?
public static void readFile(String fileName) {
if (fileName == null) // Go back to reading standard input
readStandardInput();
else {
BufferedReader newin;
try {
newin = new BufferedReader( new FileReader(fileName) );
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n"
+ "(Error :" + e + ")");
}
if (! readingStandardInput) { // close current input stream
try {
in.close();
}
catch (Exception e) {
}
}
emptyBuffer(); // Added November 2007
in = newin;
readingStandardInput = false;
inputErrorCount = 0;
inputFileName = fileName;
}
}
I had to use TextIO for a school assignment and I got stuck on it too. The problem I had was that using the Scanner class I could just pass the name of the file as long as the file was in the same folder as my class.
Scanner fileScanner = new Scanner("data.txt");
That works fine. But with TextIO, this won't work;
TextIO.readfile("data.txt"); // can't find file
You have to include the path to the file like this;
TextIo.readfile("src/package/data.txt");
Not sure if there is a way to get it to work like the Scanner class or not, but this is what I've been doing in my course at school.
The above answer (about using the correct file name) is correct, however, as a clarification, make sure that you actually use the proper file path. The file path suggested above, i.e. src/package/ will not work in all circumstances. While this will be obvious to some, for those of you who need clarification, keep reading.
For example (and I use NetBeans), if you have already moved the file into NetBeans, and the file is already in the folder you want it to be in, then right click on the folder itself, and click 'properties'. Then expand the 'file path' section by clicking on the three dots next to the hidden file path. You will see the actual file path in its entirety.
For example, if the entire file path is:
C:\Users..\NetBeansProjects\IceCream\src\icecream\icecream.dat
Then, in the java code file itself, you can write:
TextIo.readfile("src/icecream/icecream.dat");
In other words, make sure you include the words 'src' but also everything that follows the src as well. If it's in the same folder as the rest of the files, you won't need anything prior to the 'src'.
So I am trying to copy one file from one place to the other using the solution found here :
Copying files from one directory to another in Java
My code creates the new directory but cant seem to find the file ,even though the landedtitlesFile is pointing to the proper path and file. I always get my "blast" comment in case you were wondering if my program gets to the end of the method.
Thank you for your time and patience.
private File landedtitlesFile = new File("C:\\Program Files (x86)\\Steam\\SteamApps\\common\\Crusader Kings II\\common\\landed_titles\\landed_titles.txt");
private String modPath = "C:\\Users\\Bernard\\Documents\\Paradox Interactive\\Crusader Kings II\\mod\\viking";
public void createCopyLandedTitles(Boolean vanilla){
if (vanilla == true) {
File dir = new File(modPath + "\\common\\landed_titles");
dir.mkdir();
try{
FileUtils.copyFile(landedtitlesFile,dir);
}
catch (IOException e ){
System.out.println("blast");
}
}
copyFile expects the second parameter to be the destination file, not a destination directory. You need to give it the target name of the file within that directory:
FileUtils.copyFile(
landedtitlesFile,
new File(dir, landedtitlesFile.getName());
Exception objects generally contain some information on the cause. If you print out the exception with e.printStackTrace(); (or rethrow it up the stack with throw new RuntimeException(e);) then you will be able to see what it says.
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();
}
}
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.