I am working on a basic game similar to Break Out and I plan to use a text file to store level data on where various objects should be located when a level is rendered onto the screen. Here is the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LevelData {
public LevelData(){
readFile();
}
public void readFile(){
try{
BufferedReader in = new BufferedReader(new FileReader("Levels"));
String str;
while((str = in.readLine()) != null){
process(str);
in.close();
}
}catch (IOException e){
System.out.println("File Does Not Exist");
}
}
private void process(String str){
System.out.println(str);
}
}
This following code, based off of previous research, should access the file "Levels" that is located in the same package as the Java class, but if the program cannot access the file then it should print "File Does Not Exist" to the console. I have created a file called "Levels" that is located in the same package as the Java class but whenever I run this class, it does not read the file properly and it catches the Exception.
Does anyone have any ideas on why it cannot access the proper file? I have already looked on various other threads and have found nothing so far that could help me.
Thanks in advance
Your Levels file probably doesn't want to be in the same package as the class, but rather, in the same directory from where your java program was run.
If you're using eclipse, this is probably the project directory.
Your issue is probably the lack of a file extension!
BufferedReader in = new BufferedReader(new FileReader("Levels.txt"));
In case you are running from Eclipse, the file should be accessed like new FileReader("src/<package>/Levels") .
Closing the inputstream in.close(); should happen outside the while loop.
As you said you plan to use a text file to store level data. One way to solve the problem is to provide relative path to the file while storing and while reading the file use the relative path to read the file. Please don't forget to specify the extention of the file.
I see a few problems, the first one being there's no file extension. Second, the in.close() is in the while loop, and since you are planning on storing high scores, I would recommend you would use an ArrayList.
It is always a good practice to specify the absolute path name of the file if the file is external to your jar file. If it is part of your jar file, then you need to get it using 'getResourceAsStream()'.
Related
I am trying to delete all files in a folder:-
import java.io.*;
public class AddService {
public static void main(String args[]){
File folder=new File("inputs");
File[] listOfFiles=folder.listFiles();
for(File file:listOfFiles){
if(file.delete())
System.out.println("File deleted");
else
System.out.println("File not deleted");
}
}
}
I am getting response "File not deleted" and the file isn't getting deleted. What's wrong with my code?
There are any number of reasons why a file cannot be deleted; it may not exist, it may be a non-empty directory, you may not have closed all resources using it, and your program may not have permission to do so, to name a few.
Unfortunately the File.delete() method provides very little information as to why; it's pretty much up to you to poke around and figure it out. But there's good news; you don't want to use File in the first place.
Java 7 introduced the new java.nio.file package which is a much more robust file access API. It provides the concept of an abstract Path and separates concrete operations into the Files class, in particular it provides Files.delete() which is documented to raise clear exceptions describing the reasons deletion might fail.
Use Path and Files; you'll be glad you did.
Try giving the full path in this statement: "File folder=new File("inputs");"
Use try-catch block and print the exception, if any
I figured it out, I was using a FileReader to read contents of the file which I didn't close. Sorry for not providing the entire code
Java library delete function does not delete a directory if its not empty.
Try recursion over that to delete all sub-directories and files.
OR use some external library like apache commons io
File file = new File("/your/path/here");
FileUtils.deleteDirectory(file);
import org.apache.commons.io.FileUtils;
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version><!-- check latest version-->
</dependency>
Try calling Garbage Collector before deleting file.
EDIT: In think that file is being used by other processes while deleting and because of this you can't delete the file you want.
There is nothing wrong with your code except you should give the full path.
try this : File folder=new File("C:\\inputs");
instead of this line : File folder=new File("inputs");
You have not given the full path for the folder.
Also note to use forward slash.
try{
File folder=new File("C:/xxxx/xxxx/xxxx/inputs");
File[] listOfFiles=folder.listFiles();
for(File file:listOfFiles){
if(file.delete())
System.out.println("File deleted");
else
System.out.println("File not deleted");
}
}
catch(Exception e)
{
System.out.println(e.printStackTrace());
}
Always use try-catch for code that contains methods which throws Exceptions.
I'm using Eclipse (SDK v4.2.2) to develop a Java project (Java SE, v1.6) that currently reads information from external .txt files as part of methods used many times in a single pass. I would like to include these files in my project, making them "native" to make the project independent of external files. I don't know where to add the files into the project or how to add them so they can easily be used by the appropriate method.
Searching on Google has not turned up any solid guidance, nor have I found any similar questions on this site. If someone knows how to do add files and where they should go, I'd greatly appreciate any advice or even a point in the right direction. Also, if any additional information about the code or the .txt files is required, I'll be happy to provide as much detail as possible.
UPDATE 5/20/2013: I've managed to get the text files into the classpath; they're located in a package under a folder called 'resc' (per dharam's advice), which is on the same classpath level as the 'src' folder in which my code is packaged. Now I just need to figure out how to get my code to read these files properly. Specifically, I want to read a selected file into a two-dimensional array, reading line-by-line and splitting each line by a delimiter. Prior to packaging the files directly within the workspace, I used a BufferedReader to do this:
public static List<String[]> fileRead(String d) {
// Initialize File 'f' with path completed by passed-in String 'd'.
File f = new File("<incomplete directory path goes here>" + d);
// Initialize some variables to be used shortly.
String s = null;
List<String> a = new ArrayList<String>();
List<String[]> l = new ArrayList<String[]>();
try {
// Use new BufferedReader 'in' to read in 'f'.
BufferedReader in = new BufferedReader(new FileReader(f));
// Read the first line into String 's'.
s = in.readLine();
// So long as 's' is NOT null...
while(s != null) {
// Split the current line, using semi-colons as delimiters, and store in 'a'.
// Convert 'a' to array 'aSplit', then add 'aSplit' to 'l'.
a = Arrays.asList(s.split("\\s*;\\s*"));
String[] aSplit = a.toArray(new String[2]);
l.add(aSplit);
// Read next line of 'f'.
s = in.readLine();
}
// Once finished, close 'in'.
in.close();
} catch (IOException e) {
// If problems occur during 'try' code, catch exception and include StackTrace.
e.printStackTrace();
}
// Return value of 'l'.
return l;
}
If I decide to use the methods described in the link provided by Pangea (using getResourceAsStream to read in the file as an InputStream), I'm not sure how I would be able to achieve the same results. Would someone be able to help me find a solution on this same question, or should I ask about that issue into a different question to prevent headaches?
You can put them anywhere you wish, but depends on what you want to achieve through putting the file.
A general practice is to create a folder with name resc/resource and put files in it. Include the folder in classpath.
You can store the files within a java package and read them as classpath resources. For e.g. you can add the text files to a java package say com.foo and use this thread to know how to read them: How to really read text file from classpath in Java
This way they are independent of the environment and are co-packaged with code itself.
Add the files in the projects classpath.(you can find the class path of the project by right click the project in eclipse->Build Path->configure build path)
I guess you want an internal .txt file.
Package Explorer => Right Click at your project => New => File . Then text a file name and Finish it.
The path in your code should look like this:
Scanner diskScanner = new Scanner(new File("YourFile"));
Lets say I'm making a program that needs to copy all the lines in a .txt file within my .jar file. it is in the package program.files and it is named text.txt. I've been looking all over the internet, and i cant find what I'm looking for. i think that this idea:
public String readSpecificFromJar(String dir, int line) {
String read = null;
try {
InputStream in = getClass().getResourceAsStream(dir);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
/**
* declare string variable and prime the read
*/
read = bufferedReader.readLine();
for (int i = 1; i < line; i++) {
read = bufferedReader.readLine();
}
bufferedReader.close();
} catch (IOException ioexception) {
Dialogs.fail("Could not read txt file from the JAR!!! Error Code: 06");
}
return read;
}
would work, but i tried that and it gave me all kinds of errors. what i think the problem would be is declaring the InputStream in the way it does it want the file to be right there with the Main method. how would i change this so it is not the case? thanks in advance!
EDIT:
due to some confusion, i want to clear this up. for the String dir i am entering files/text.txt. it wont work. how do i fix this?
EDIT 2:
OK i feel like the problem isn't getting across, and I'm kinda getting aggravated, mainly because I'm pretty tired. the code that WORKS for a different program is up above, where the dir is simply "text.txt"
THIS DOESN'T WORK FOR WHAT I'M DOING AND IM NOT SURE WHY. again, the file is IN THE CLASSPATH so dir is only "text.txt". I want my .txt file to be "files/text.txt". How do i do this?
EDIT 3:
I dont know if i mentioned it, but my .txt file is INSIDE my jar. just to clear up the confusion. so really, the path of the .jar file shouldn't matter, as in I shouldn't have to type it in with the dir. also, the main class is in the package main and the .txt file is in the package files all within the same program named copy. also, i tried moving the txt file to the same package as the main class, also didn't work.
EDIT 4:
by the way, the package that holds the method for reading from the jar is IO. as in the class io is inside the package IO. all of my files such as images and txt are in the package files. just thought id clear that up. i tried moving the txt file to the package of the io class, and that worked, but if its in any other package, even if i include the package name in the dir it wont work. any ideas as to why?
The .txt file should be in The root directory of dir is the same directory where your class file is located in.
EDIT: due to some confusion, i want to clear this up. for the String
dir i am entering files/text.txt. it wont work. how do i fix this?
What is the path of the class? (the class that contains readSpecificFromJar()) If the .class file and the .txt file are both in the same directory, then you should make it like this:
dir = "text.txt";
EDIT 4: by the way, the package that holds the method for reading from
the jar is IO. as in the class io is inside the package IO. all of my
files such as images and txt are in the package files. just thought id
clear that up. i tried moving the txt file to the package of the io
class, and that worked, but if its in any other package, even if i
include the package name in the dir it wont work. any ideas as to why?
Try this:
dir = "../files/text.txt";
I believe this would work if your structure is as follows:
javaApp.jar
|
_____|_____
| |
files IO
| |
| |
text.txt io.class
I am trying to make this program that will write a file to the users computer but am having trouble really, I want to write a file called desktop.bat that I have to the c:/ directory but it doesn't seem like it's working. this is the code:
package javawriter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class JavaWriterObject {
public void TryThis(){
try{
File file = new File("C:\\Desktop.bat");
if (file.exists()){
System.out.println("The file exists \ndirectory is found");
}else{
System.out.println("file is not found yet ".concat("file will be created"));
file.createNewFile();
}
FileWriter out = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(out);
writer.write();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
Do I have to write a String for the writer.write(); or can I do something where I can write the file I want instead?
Java 7's Files.copy method helps you copy a file from one location to another.
If you're using an older version of Java, you will need to either read the original file in yourself and copy its contents into your new file, or you'll have to use a third-party library. See the answers to this question for several good solutions, including using Apache Commons IO FileUtils or just the standard Java API.
Once you've decided how you want to copy the file, you might run into another problem. By default, Windows 7 will prevent you from writing to certain directories such as C:\. You can try writing to a different directory, such as in the temp directory or any location within the user's home directory. If you must write to C:\, the easiest solution (aside from creating the file ahead of time in Windows and overwriting it in your program, which probably defeats the purpose) is to disable UAC and make sure your user account has write permission on that directory--but this, of course, has security implications.
You have to get the content you want to write from somewhere, either a String literal in your application, or, the preferred method would be from a resource (bundled along with your application) via. YourClass.class.getResourceAsStream(name).
Copying an input stream to a file is a bit of effort, Guava can copy, but, if you're using Guava, you may as well copy directly from the resource to the file.
Im trying to write a program to read a text file through args but when i run it, it always says the file can't be found even though i placed it inside the same folder as the main.java that im running.
Does anyone know the solution to my problem or a better way of reading a text file?
Do not use relative paths in java.io.File.
It will become relative to the current working directory which is dependent on the way how you run the application which in turn is not controllable from inside your application. It will only lead to portability trouble. If you run it from inside Eclipse, the path will be relative to /path/to/eclipse/workspace/projectname. If you run it from inside command console, it will be relative to currently opened folder (even though when you run the code by absolute path!). If you run it by doubleclicking the JAR, it will be relative to the root folder of the JAR. If you run it in a webserver, it will be relative to the /path/to/webserver/binaries. Etcetera.
Always use absolute paths in java.io.File, no excuses.
For best portability and less headache with absolute paths, just place the file in a path covered by the runtime classpath (or add its path to the runtime classpath). This way you can get the file by Class#getResource() or its content by Class#getResourceAsStream(). If it's in the same folder (package) as your current class, then it's already in the classpath. To access it, just do:
public MyClass() {
URL url = getClass().getResource("filename.txt");
File file = new File(url.getPath());
InputStream input = new FileInputStream(file);
// ...
}
or
public MyClass() {
InputStream input = getClass().getResourceAsStream("filename.txt");
// ...
}
Try giving an absolute path to the filename.
Also, post the code so that we can see what exactly you're trying.
When you are opening a file with a relative file name in Java (and in general) it opens it relative to the working directory.
you can find the current working directory of your process using
String workindDir = new File(".").getAbsoultePath()
Make sure you are running your program from the correct directory (or change the file name so that it will be relative to where you are running it from).
If you're using Eclipse (or a similar IDE), the problem arises from the fact that your program is run from a few directories above where the actual source is located. Try moving your file up a level or two in the project tree.
Check out this question for more detail.
The simplest solution is to create a new file, then see where the output file is. That is the correct place to put your input file into.
If you put the file and the class working with it under same package can you use this:
Class A {
void readFile (String fileName) {
Url tmp = A.class.getResource (fileName);
// Or Url tmp = this.getClass().getResource (fileName);
File tmpFile = File (tmp);
if (tmpFile.exists())
System.out.print("I found the file.")
}
}
It will help if you read about classloaders.
say I have a text file input.txt which is located on the desktop
and input.txt has the following content
i came
i saw
i left
and below is the java code for reading that text file
public class ReadInputFromTextFile {
public static void main(String[] args) throws Exception
{
File file = new File(
"/Users/viveksingh/desktop/input.txt");
BufferedReader br
= new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
output on the console:
i came
i saw
i left