I am doing some algorithmic problems on the website USACO, and for every submission they want us to make two files for input and output to test values. So if the problem was called "test", they would want users to make the files "test.in" and "test.out" which requires them to change their extensions to ".out" and ".in". How do I change their extensions from ".txt" to ".in" or ".out"?
Note: I am using Windows 8
Thank you
To make Java read files in Eclipse
One must make sure that the words typed in the code and in the name of the file match each other.
For example: The file referenced in must exist.
BufferedReader f = new BufferedReader(new FileReader("test.in"));
Also, you have to make the file under the project folder (in Eclipse or manually in Windows Explorer) because that folder is the directory at for that code, and if it is not in the folder the code will not be able to read it. You can also right-click the project to import files into the folder.
My reference: Trial and Error
http://www.coderanch.com/t/439615/java-io/java/Eclipse-won-read-text-file
Related
This question already has answers here:
Reading a plain text file in Java
(31 answers)
Closed 2 years ago.
My project structure is like this:
Project
App
x.java
files
file.txt
main.java
I want to access file.txt via x.java.. My code:
File file = new File("file.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
out += sc.nextLine();
if (out.isEmpty()) out = "NOTHING";
but gives me NullPointerException.
If this file is supposed to be part of your app the way class files are (so, effectively read-only, an asset that you pack in with the rest. Think texture maps for games, or icons for user interfaces), use getResourceAsStream, as the resource in question may not even be a file (java projects tend to ship as jars, and an entry in a jar is not a file!).
If not, well, then figure out a way to get the full path info into your code, because it's not going to magically figure out that you have a dir structure with "App" and "files", which is non-standard. (the standard route is src/main/java/pkgname/Type.java for java files, and src/main/resources/pkgname/open.png for assets that just need to be there (don't need compiling).
If you set up a project in your favourite IDE according to this structure and configured using e.g. maven or gradle, then getResourceAsStream works during dev time, and also at runtime, even if the resource is inside the jar.
Basically when you read the file "file.txt", you don't provide with an absolute path so the operating system will look for a file in the current directly. That is the one where your program started.
I get you didn't start the program in the folder "files" but in another folder like maybe the folder "Project". In that case the path to use would be "files/file.txt".
I solved it !
First, I used
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
to detect the whole path.. Then I appended the directory.getAbsolutePath() with the filename so it becomes directory.getAbsolutePath()+"file.txt"
I used the normal way to read a file by using the scanner and scanner.readLine() to read the file !
This answer
Has helped me
I made a small Java program for academic purposes, its main focus is to read some .txt files and present the information to the user. These files are present in the resources folder, under the src folder.
The program runs as intended when launched from Eclipse.
Using the Launch4j app I was able to successfully create an exe which runs fine and does what's intended, up until I try to read the .txt files I have in the resources folder, which appears not to be able to reach.
I'm guessing that when I launch the exe the run time path would change to where the exe was created, so I created the program in a desktop folder and specified this path in the program, but that doesn't seem to solve the situation.
As an alternative, I moved the .txt files out of the program and once again created the exe in a desktop folder with said .txt files, linked the program to this path and once again it didn't work.
The command used to get the .txt files is:
Files.readAllLines(Paths.get(doc)).get(line)
And doc is simply the path to the intended .txt file.
It's worth noting that I have no previous experience in Java and throughout the development of the program I tried my best to use commands I'd fully understand and to keep it as simple as possible. I hope the solution can be along these lines! I'm very confident this must be a rookie mistake, but I can't seem to find the solution to this specific problem anywhere.
The paths to files in Eclipse are different than the paths to files in an .exe or JAR file.
I will let this other user explain it because I am lazy :p
Rather than trying to address the resource as a File just ask the
ClassLoader to return an InputStream for the resource instead via
getResourceAsStream:
InputStream in = getClass().getResourceAsStream("/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
As long as the file.txt resource is available on the classpath then
this approach will work the same way regardless of whether the
file.txt resource is in a classes/ directory or inside a jar.
The URI is not hierarchical occurs because the URI for a resource
within a jar file is going to look something like this:
file:/example.jar!/file.txt. You cannot read the entries within a jar
(a zip file) like it was a plain old File.
This is explained well by the answers to:
How do I read a resource file from a Java jar file?
Java Jar file: use resource errors: URI is not hierarchical
The original post is here, all credit to its author.
Fixing your URL should let you read from that file when you are using the .exe.
EDITED FOR CORRECTION. Thanks #VGR (see comments) for correcting my mistake.
I'm trying to read a txt file that is in a folder called "levels". The class where I'm using the Scanner is in src/anotherPackageName, if that's relevant. When I execute:
Scanner s = new Scanner(new File("levels/level0")); //adding .txt doesn't fix
it throws an exception. I don't want to use an absolute path, but rather relative to the project if possible. This is my folder structure:
D:\OneDrive\Folder\AnotherFolder\ProjectName
ProjectName
src
packageOne
ClassWhereImUsingScanner
OtherClasses
(...)
levels
level0
level1
(...)
So in order to access a file you could do something like this:
FileReader sourceFile = new FileReader("levels/level0.txt");
BufferedReader inStream = new BufferedReader(sourceFile);
String Line = inStream.readLine();
Then, you can use a tokenizer depending on your data and how you want to store it.
You could see this example: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
Bear in mind that in most Java code, the end state of the project is not run from the IDE, but rather from some production system (e.g. an app or a server). In that case, your development source code structure won't be available.
There are two main ways to read text files or other resources in Java: either you can find the path to the actual file, in which case you need to deal with possibly not running out of your development source tree, or else you need to find a way to bundle the text file into your project.
Most Java projects end up getting compiled into some kind of archive, either a JAR file or a WAR file (for web applications) or something like an Android APK. In most cases you can add your own text files into the project archive. (For example, in a Maven project, if you just put your text file in the src/main/resources folder it should be included in the compiled JAR.)
However, in this case, the text file is no longer a separate file on disk, but rather a blob of data inside an archive. You could unzip the archive to get an actual File object, but that's wasteful if all you actually need is to read the bytes.
Thus, the most common way that text files like this are read is by using the existing ClassLoader mechanism, which is what is reading the .class files from disk (or from an archive, or over the network, or whatever). The ClassLoader already knows how to load bytes that are "alongside" your compiled code, so you can just make use of that.
In your case, you should be able to do something like this:
Scanner scanner = new Scanner(
getClass().getResourceAsStream("/path/to/file.txt"));
In this case, the /path/to/file.txt path is relative to the path your class was loaded from. E.g. if your class is named my.package.Foo then the actual class bytes will be in a folder (either a filesystem folder or in a JAR file or something) named my/package/Foo.class -- in this case, the path/to/file.txt and my/package/Foo.class will be relative to the same root.
See the documentation on resources for more information.
Usually the path is relative to your execution, but it also depends on your project setup on eclipse, could you send more information about you directory structure?
Based on you structure try something like this:
Scanner s = new Scanner(new File("../levels/level0"));
For some unusual reason, when I am using FileWriter for Java Netbean, the file gets written into this directory:
C:\Users\myname\AppData\Roaming\NetBeans\7.2\config\GF3\domain1
rather than to my working directory, which is at the desktop.
I used this code to check my User Directory, and it returns this:
System.out.println(System.getProperty("user.dir"));
INFO: C:\Users\myname\AppData\Roaming\NetBeans\7.2\config\GF3\domain1
which is obviously NOT my working directory where my source code is. I thought I could have accidentally configured Netbeans to change the directory, but I checked through NetBeans menu and can't figure out how to undo this.
I have never had this problem before in my previous projects. As simple as the following code, the file should appear in my working directory.
File file = new File("myFile.xml");
Instead now I'm being forced to enter the path name to make the file save into my working directory, which is not going to be dynamic if I change computer.
String dir = "C:\\Users\\myname\\Desktop\\Assignment\\IRAssignmentJ\\";
File file = new File(dir + "myFile.xml");
Please enlighten me how do I solve this.
rather than to my working directory, which is at the desktop
No it isn't. The current working directory is whereever the file got saved, by definition. If Netbeans chooses to change directory to where it was saved, there's nothing you can do about it. If you want it in your home directory, there is a system property for that. If you want it saved somewhere else, use a full pathname.
But the behaviour of the application under Netbeans is of little interest. What matters is when you run it as though standalone, like a customer would.
After looking at a couple of audio libraries, I settled on EasyOgg. Most of the samples report that you play sounds like this:
new OggClip("mysfx.ogg").loop();
This crashes with Couldn't find: mysfx.ogg at runtime. I tried several things:
Plain filename
Relative path from my project root directory
Forward-slashes and backslashes
I can't figure out where exactly the file goes, and how to specify the name. It seems like they should be somehow embedded in my application JAR. (I just have them sitting on the file system.)
I fiddled around with it for a while and came up with a solution using InputStreams:
FileInputStream stream = new FileInputStream("file.ogg");
OggClip clip = new OggClip(stream);
This works without including the files in the jar.
I'm not familiar with EasyOgg, but the first thing I would do is pass in the complete location to the file as a sanity check.
new OggClip("/home/someuser/audio/mysfx.ogg").loop();
If you can't count on java being run from the same location every time, you can use an environment variable to point to the location that your files are sitting in.
new OggClip(System.getenv("MY_APP_HOME") + "/audio/mysfx.ogg").loop();
As far as getting to a resource from inside a jar file, have you tried getResource()?
See: Access file in jar file?
I discovered that the OGG files need to be in the JAR file. This is clear from the working zip samples I found on the interwebz.
To use Gradle to zip up every .ogg file in audio, I add this to my jar task:
from fileTree(dir: '.', include: 'audio/**/*.ogg')
This works, except when I debug from Eclipse. A better solution is to create a separate project (I called mine EmbeddedResources) which creates a JAR that only contains .ogg files. Then, I reference this project from my game project, and I'm done.