NetBeans Java Project Path of Text File - java

I have the following code to read a text file.
public static void main(String[] args)
{
try
{
Scanner in = new Scanner(new FileReader("input.txt"));
while(in.hasNext())
{
System.out.println(in.next());
}
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have my project structure set up as follows:
build/ directory contains class
dist/ directory contains the jar file
src/ directory contains source
input.txt the text file to read
If I put my textfile input.txt into a directory called test which is of the same directory as build, dist, and src, what should go into the parameter of filereader so that I can still find this file?

When running inside the Netbeans IDE the working directory is the root of the project, so to answer your question, "test/input.txt".
Note however that while this is perfectly fine for testing code, working with relative paths like this in final (production) code can be trickier. In those cases wrapping the file as a resource in the jar and opening it as a resourcestream may be a better solution, or of course working with absolute paths.

If you know the name of your subdirectory, just use
Scannner in = new Scanner(new FileReader("test/input.txt"));

Related

About citing external files in java application

I am writing a java application, in which I am automatically importing external csv files in background to do the computation. But the problem is that I am using "absolute" file path in my java program, the generated jar file will not work in another computer. Is there anyway in java to use a kind of "working directory path" so that I can still run the jar file in another computer as long as I put the csv files I'd like to import in the same folder with the jar file?
Thanks!
You can read a file using its name like
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"))) {
String line;
while ((line=br.readLine())!=null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Here text.txt should be in the same working directory where the jar was executed.
You can also read the directory name from the command line, using the command line arguments like
public static void main(String[] args) {
//check if there were any command line arguments
if (args.length > 0) {
// args[0] is the first command line argument unlike C where args[0] would give u the executable's name
} else {
System.err.println("Usage: java -jar <jar_name> [directory_names..]");
}
}
You can also have a configuration file such as a properties file to read the directory names.
new File(".") give you the relative path
you can write relative path like that :
File file = new File(".\\CSVs\\myfile.csv");
System.getProperty("user.dir") will return you the working directory.
System.getProperty("user.dir")+"\\myfile.txt"
More informations here :system properties, oracle docs

Write to a .txt file in a package

I would like to write to a .txt file that is inside a package. I can get it to read from the exact location the .txt file is stored but not from inside the package. I'm assuming it is using class loaders but I cannot seem to get it to work.
Here is what I have so far.
public void writeFile(String fileLocation) {
Writer output = null;
File file = new File(fileLocation);
try {
output = new BufferedWriter(new FileWriter(file));
output.append("WRITING TEST");
output.close();
} catch (IOException ex) {
System.out.println("Couldn't write to file.");
}
}
Then I use this in another class to write.
WriteFile writeFile = new WriteFile();
writeFile.writeFile("src/com/game/scores.txt");
I understand that if using class loaders you remove "src/" because that will no longer exist when the program is compiled in a .jar.
It is not possible to write or update a file inside jar. Since jar itself is a file.
Please refer this link.
Write To File Method In JAR
You could use a class in that package to give you the location of the folder.
Try something like
public URL getPackageLocation() {
return getClass().getResource(".");
}
This should give you the location of the folder from which this method is being called from.
From the comments you already know that you cann't write to a file, which resides in a JAR file. At best what you can do, is creating your file, relative to the path where the JAR is located like bellow:
mylocation
|-- my-jar.jar
|-- com
|--game
|--myfile.txt
I would like to write to it to update the scores in my game as the
user goes through the levels.
While it might be possible to write to the JAR file, I don't recommend it for this use case. Just write it somewhere at:
Path userdir = Paths.get(System.getProperty("user.home"), ".myApp", "<my app version>");
You can't write into Jar file. Writing into Jar file is not recommendable. You can write outside the jar file.
Please refer this and this stack overflow question for more details.

Why isn't java finding my file

Trying to learn how to read text files in Java. I have placed the text file within the same folder as IdealWeight.java. Am I missing something here?
IdealWeight.java
package idealweight;
import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class IdealWeight
{
public static void main(String[] args)
{
Scanner fileIn = null; //Initializes fileIn to empty
try
{
fileIn = new Scanner
(
new FileInputStream
("Weights.txt")
);
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
}
}
You could also put the file in the classpath and then do this:
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("Weights.txt");
Just another idea.
The java file IO system does not look for the file in the same directory as the class, but in the "default" directory for the application. Any application you run has a directory that it regards as its default, and that's where it would attempt to open this file. Try putting a full pathname to the file.
Or put the file you want to read in a directory, and run the application from that directory (in a terminal window) with "java IdealWeight".
You need to put Weights.txt in your working directory, not in the directory with the source file. If you're using Eclipse or a similar IDE, the this is probably the project root. As per this answer, you can use this snippet to get the full path to your working directory:
System.out.println("Working Directory = " + System.getProperty("user.dir"));
Check the result of running that command, and that should tell you where to put your text file. Once you have the text file in the right place then the code you posted should work fine.

java.io.FileNotFoundException (File not found) using Scanner. What's wrong in my code?

I've a .txt file ("file.txt") in my netbeans "/build/classes" directory.
In the same directory there is the .class file compiled for the following code:
try {
File f = new File("file.txt");
Scanner sc = new Scanner(f);
}
catch (IOException e) {
System.out.println(e);
}
Debugging the code (breakpoint in "Scanner sc ..") an exception is launched and the following is printed:
java.io.FileNotFoundException: file.txt (the system can't find the
specified file)
I also tried using "/file.txt" and "//file.txt" but same result.
Thank you in advance for any hint
If you just use new File("pathtofile") that path is relative to your current working directory, which is not at all necessarily where your class files are.
If you are sure that the file is somewhere on your classpath, you could use the following pattern instead:
URL path = ClassLoader.getSystemResource("file.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
The JVM will look for the file in the current working directory.
Where this is depends on your IDE settings (how your program is executed).
To figure out where it expects file.txt to be located, you could do
System.out.println(new File("."));
If it for instance outputs
/some/path/project/build
you should place file.txt in the build directory (or specify the proper path relative to the build directory).
Try:
File f = new File("./build/classes/file.txt");
Use "." to denote the current directory
String path = "./build/classes/file.txt";
File f = new File(path);
File Object loads, looking for match in its current directory.... which is Directly in Your project folder where your class files are loaded not in your source ..... put the file directly in the project folder

Changes printed to a file aren't being saved

try{
private fileWriter= new PrintWriter(new FileWriter(file.txt));
fileWriter.print("hello world");
System.out.println("file written");
fileWriter.close();
}
catch (IOException e){
e.printStackTrace();
} finally {
}
I have this text file in my source folder. So far, there haven't been any errors with accessing it. However, when I close the program or after when the files should have been written when I open the text file I don't find them there, however I did check the bin folder ocne and it seemed to print hello world to the temp copy there.
I want the changes it makes to be permanent.
You have a couple of problems in your code. Correcting/simplifying it to the following:
public static void main(String[] args) throws IOException {
PrintWriter fileWriter = new PrintWriter(new FileWriter(new File("file.txt")));
fileWriter.print("hello world");
System.out.println("file written");
fileWriter.close();
}
makes it create the file as expected. Try that out, and if it doesn't behave the way you're expecting, then explain how. Note that when you give a relative file path, it resolves the path against your current working directory. If the file is being written somewhere you don't expect, this is probably why.
The file in the bin folder is not a temp file, it is the file you are actually writing. If you want to write to the file in the source folder you have to use it's correct file path when opening the file for writing. Java always computes relative paths to the folder you started your application in. So your application is probably started in the bin folder and writes to file.txt there.
Maybe try using the append boolean in the FileWriter constructor
public FileWriter(String fileName, boolean append)
...and I think eclipse will use the bin folder as its default classpath so its no surprise the file is written there.
I hope that helps :)
Since the code was fine going to the package explorer --> project --> properties --> java build path --> source --> checking the box that says "allow outputs for source folders"

Categories

Resources