This question already has answers here:
Reading a .txt file using Scanner class in Java
(11 answers)
Closed 3 years ago.
I have an assignment from my teacher i have make a serial program into a parallel with OMP.It's the Barnes-Hut one and its the first time i'm using netbeans.
I have a text file with someone numbers and i gotta import it into the project so it can use the values the text file has.How can i import the example.txt into netbeans?
I've tried this but it doesn't work
File myFile = new File("example.txt");
It also contains a scanner
public static void main(String[] args) {
// for reading from stdin
Scanner console = new Scanner(System.in);
Make sure your text file is in the classpath
You have a number of choices.
1. Relative Path
You can use a relative path. This means you take your current "working" location and look for the file from there, this is basically what you're doing now.
The problem with this is, the "working" location changes, and is based on the location from which the program is executed. Remember, the location of the class is not the same as the "working" location.
Netbeans "default" "working" location is usually the root directory of the project. There are ways you can configure Netbeans to use a specific "working" location, but you need to consider what happens when you're no longer running in Netbeans.
So a "simple" solution would be too drop the file into the Netbeans project directory. A slightly more advance solution would be to configure the project's "working" directory to a location containing the file
2. Absolute Path
This is when you use a fully qualified path from the a root location to the file (ie C:\some\place).
The problem with this is, rarely are this paths the same from one computer system to another and you need to remember to place the file into this location each time.
2.1 A "well known" location
A form of the absolute path solution is to place the file into a "well known" location, typically based on the OS.
For example, on Windows, you would typically use something like {user.home}\AppData\Remote\{name of your application}.
This would allow you to place the file in, what is essentially a "static" location and load it when ever you needed to.
But, this is probably over kill for your needs
3 Embedded resource
A more common solution is to "embed" the resource with your application. Essentially, this is placing the file within the applications class path, which allows the Java runtime to locate it.
In Netbeans, this means putting the file within the src directory, preferably in a subdirectory, like resources for example.
Then, when you want to read the file, you'd need to use Class#getResource(String) or Class#getResourceAsStream(String) to gain access to it.
So, based on the available information, and the example above, you might do something like...
try (InputStream is = YourClass.getResourceAsStream("/resources/example.txt")) {
// Read the file...
} catch (IOException exp) {
// Handle the exception
}
Just remember, this renders the resource "read-only" (at least for context of this simple example)
Related
This question already has answers here:
How to list the files inside a JAR file?
(17 answers)
Closed 1 year ago.
This method does not apply:
Files.walk(Paths.get("folder name"))
Because when the app is running, packaged as a jar, it does not contain File objects.
Is there a method for an app to walk through all the contents of one of its packages while it runs?
There is; open the jar file (using java.io.JarFile) and walk through the entries returned by entries(). There's also JarInputStream if your jar is being streamed in from elsewhere.
But, it sounds like you have equated 'jar file' with 'my application, at runtime'.
That's a tricky move. For starters, figuring out your own jar is possible but a little hacky, and more importantly, it then means your app straight up fails to work unless it is in jar form. This complicates deployment, development, and debugging.
There is no need to do it this way.
You can ask java for resources from 'whereever it is currently picking up class files'. A class file is a resource crucial to the running of your application. So is e.g. an icon file for a GUI app. Both should be coming from the same place, and where that is? That's abstracted away, and you should follow along with the abstraction, so that the 'load resource' code works just as well in debugging as it does at runtime.
The system for this is MyClass.class.getResource("file.txt") which will look for file.txt in the same place MyClass.class is located, even if it is in jar files, generated live, or obtained from a BLOB object in a database someplace, or streamed over a network.
The downside is, this system does not have an abstraction for listing files. Only for getting resources with a specific name.
The SPI system is the solution: Make a file that lists (one resource per line) the resources - instead of 'list dir', you 'parse each line of CONTENTS.txt' for the equivalent operation. You can then use annotation processors, if you must, to automatically create and maintain this content file.
ServiceLoader is baked into the JDK itself, but it's designed to load, specifically, class files and not other resources. But the principle is trivial and can be handwritten in about 5 lines of code.
You can iterate the contents of any ZIP / JAR file using Files / NIO, but you need to access the ZIP filesystem. Then you can call Files.find or Files.walk on the contents of the ZIP / JAR archive.
For example this will print the contents of every Path in a jar:
Path zip = Path.of("your.jar");
BiPredicate<Path, BasicFileAttributes> predicate = (p,a) -> true;
try (FileSystem fs = FileSystems.newFileSystem(zip)) {
for (Path root : fs.getRootDirectories()) {
try(Stream<Path> stream = Files.find(root, Integer.MAX_VALUE, predicate)) {
stream.forEach(System.out::println);
}
}
}
Once you have a Path object from the ZIP FileSystem, you can access the contents of the entries using NIO Files calls in the normal manner such as with Files.newInputStream or Files.copy.
I know there are 2 ways of writing a pathway for a file while reading file in JAVA.
//1st way
scanner = new Scanner(new File("C:\\Users\\User\\IdeaProjects\\EDSS\\src\\file\\JobList.txt"));
//2nd way
scanner = new Scanner(new File("src/file/JobList.txt"));
But when I try to convert my format from .java to .exe(Application) with the 1st way in IntelliJ via something called "Build Artifacts", I can open the application smoothly. However, with 2nd way, I cannot open the Application and I found out that it is because of the pathway. And 1st way only allow me to run the Application in my computer only. If I copy the file to my friend's laptop with different username, for example ("C:\Users\Bernard..."), the application cannot work too and I have to manually modify the pathway in the codes to run the Application.
Is there any way to search for a pathway accurately without manually type the full length out and at the same time, the Application (.exe) can work with it?
You run into the problems with absolute and relative paths.
Your first option is an absolute path. which means you will always grab the file in a particular location on the computer but if that location does not exist you can't find it
Your second option uses relative path which will look for a file based on the starting location of your program so an exe might start from a different location then the command line you build java from.
The solution is to use relative paths and to make sure the Joblist.txt file is always in one location relative to your run location.
If you want to know where the starting path of your program is you can run the following code:
System.out.println(new File(".").getAbsolutePath())
I need to write a program that asks for the file name of a text document of number and then calculates average, median, etc., from this data set. I have written the program so that runs correctly when I input the full path such as "C:\Users\COSC\Documents\inputValues2.txt", however it will not run when I simply input inputValues2.txt. I have been researching the different between the two but am not fully understanding how to fix this. Since it is running correctly, otherwise, I don't believe it is a problem with the code, but I am new to this so I may be wrong.
Your program needs to know the full path in order to find the file. It isn't just searching your computer for the file "inputValues2.txt". It needs to know exactly how to get there. If you wanted to, you could move the file into your project folder, and then you would just be able to write "inputValues2.txt" to access it. I normally create a folder called "res" in my project folder, and then let's say I am trying to create an image:
Image i = new Image("res/img.png");
Your file should be in the class-path. That's in the same directory that your main class is in.
The suggested practice is to place it in a Resources directory inside your class-path, then you can access it via, "Resources/inputValues2.txt".
I have to write a Java Project with a Swing GUI and some smaller formal requirements like a button which does something or methods which implement something, very basic.
I have written a programm with a basic GUI including a Jtable which stores information about students(name,semester...) in a Java File.
The Problem is that the path of this java-File in my programm is relative, in my case:
public static final String pfad = "src/abgabe/";
public static final String name = "Uni";
File file = new File(pfad + name)
If I export my Programm to JAR and send it around, it wont work on other computers because only I have the Java File.
Can I change my code to make the Jar File creates a new Java file in its own root directory?
Can I change my code to make the Jar File creates a new Java file in its own root directory?
Even if you can, you shouldn't. Most OS manufacturers have been saying for years that application data should not be stored in the apps. installation directory.
Instead put the file in a sub-directory of user.home. That will be a path that:
Is reproducible.
The app. should have write permissions for.
Although the question is not directly related, the answer is, so see also How can an app use files inside the JAR for read and write?
I need to write a program that asks for the file name of a text document of number and then calculates average, median, etc., from this data set. I have written the program so that runs correctly when I input the full path such as "C:\Users\COSC\Documents\inputValues2.txt", however it will not run when I simply input inputValues2.txt. I have been researching the different between the two but am not fully understanding how to fix this. Since it is running correctly, otherwise, I don't believe it is a problem with the code, but I am new to this so I may be wrong.
Your program needs to know the full path in order to find the file. It isn't just searching your computer for the file "inputValues2.txt". It needs to know exactly how to get there. If you wanted to, you could move the file into your project folder, and then you would just be able to write "inputValues2.txt" to access it. I normally create a folder called "res" in my project folder, and then let's say I am trying to create an image:
Image i = new Image("res/img.png");
Your file should be in the class-path. That's in the same directory that your main class is in.
The suggested practice is to place it in a Resources directory inside your class-path, then you can access it via, "Resources/inputValues2.txt".