Where do find a File in the Eclipse Project - java

I know this question has been asked before, but I have a slightly different problem.
I want to read and write to a text file which will be included in my build(.jar file) . its a Gui application java.
Where Should I place the file?
I have placed the file by creating a new Resources folder under the project. This enables me to read the file but when I attempt to write to it, it throws a FileNotFound Exception. What should I do?
I am using this code
File file = new File(this.getClass().getClassLoader().getResource("score.txt").getFile());
FileOutputStream stream = new FileOutputStream(file);
DataOutputStream write = new DataOutputStream(stream);
write.writeInt(max);
And for Input i use this :
File file = new File(this.getClass().getClassLoader().getResource("Files/score.txt").getFile());
FileInputStream input = new FileInputStream(file);
DataInputStream read = new DataInputStream(input);
System.out.println(read.readInt());
For reading this code works perfectly.

Related

Java: How to get the path of an empty resource folder [duplicate]

I am trying to write a .txt file in a resource folder but it doesn't write anything. I am able to read the same .txt file by doing:
Scanner scanner = null;
InputStream IS = MyClass.class.getResourceAsStream("/File/My FileH");
scanner = new Scanner(IS);
But when it comes to write, I have tried doing:
PrintWriter writer = new PrintWriter(
new File(this.getClass().getResource("/File/My FileH").getFile()));
writer.println("hello");
writer.close();
Any suggestions on how to write in that folder?
You can't write something in to a resource, assume that you packed your resource as a jar. Jar is only read only. You can't update that. Either you can extract the jar and edit the contents.
You can try Preferences as an alternative

Reading file from text

I have tried this a hundred different ways but keep getting a filenotfound... Put it as simple as I could and don't understand it.
File file = new File("C:/files/salesrep.txt");
FileReader fileSC = new FileReader(file);
BufferedReader br = new BufferedReader(fileSC);
The FileReader is giving me a file not found. I tried using the directory and get the same.
Try using path like this, if the file exists the shouldn't be a problem.
File file = new File("C:\\files\\salesrep.txt");
Also you can here for more specific explanation.

File is not getting copied in Java using input and output stream reader

I am working in Java platform. I need to copy a file from the package to some folders in desktop. I am using input stream and output stream classes to do it, it is doing the job pretty well inside NetBeans.
The problem is, it's not copying the file while I am running the JAR file to test the application, and it is saying NULL.
File source = new File("src/jrepo/css/bs.css");
File dest = new File(ResultPath + "/css/bs.css");
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
Your problem is with
new File("src/jrepo/css/bs.css");
The constructor for File(String) takes a full path to the file. You are using a relative path. If you are trying to read the file from the operating system, use the full path. If you are reading it from the jar file, then use this approach instead.
I found the way since I am using JavaFX, there is a problem which stops the file copying of CSS files. In order to resolve that issue just change the run time settings of the project in Netbeans. Right click the title of the project→go to Properties→Build→Packaging→uncheck the Binary Encode JavaFX CSS files checkbox and then save the project and rebuild it.

Writing to Files : Printwriter Converting Forward Slash to Backslash

Why is Printwriter doing this?
File file = new File("/files/KA.txt");
writer = new PrintWriter(file);
writer.write("HELLO");
In the above code I keep getting an error that says :
java.io.FileNotFoundException: \files\KA.txt (The network path was not found)
Except this was not my specified path? How do I then specify a file to write - usually create a new file and write to this? It also throws errors if KA.txt is not present - I ideally want to create a new file and writer to it.
Thanks
I ideally want to create a new file and writer to it.
You can simply create a file ,
PrintWriter writer = new PrintWriter("name.txt", "UTF-8");
writer.println("text");
where UTF-8 is the file encoding. and write to the file , remember it overrides if the file exists with the same name
The problem is that the parent /files directory doesn't already exist, so you must create it beforehand, using File.mkdirs.
File file = new File("/files/KA.txt");
File parentFile = file.getParentFile();
parentFile.mkdirs();
PrintWriter writer = new PrintWriter(file);
writer.write("HELLO");
writer.close();

using FileInputStream and FileOutputStream

Hi I had a couple of questions about using the FileInputStream and FileOutputStream classes.
How would FileInputStream objects locate a file it is trying to read in?
Where would FileOutputStream save a file to?
Thanks.
Strange question and I will give a strange answer.
First part: don't use either, use Files:
final Path src = Paths.get("some/file/somewhere");
final InputStream in = Files.newInputStream(src);
// ...
final Path dst = Paths.get("another/file");
final OutputStream out = Files.newOutputStream(dst);
Note that Path objects are in essence abstract: nothing guarantees that they point to a valid entry. If they don't, the Files methods above will throw a NoSuchFileException (file does not exist), or an AccessDeniedException (sorry mate, you can't do that), or any relevant exception.
Second part: File*Stream
The basics are the same: if you are stuck with Java 6 you have to use File instead of Path, but File is as abstract as Path is; it may, or may not, point to a valid location.
When you issue:
final String dst = "/some/file";
new FileOutputStream(dst);
internally, FileOutputStream will create a File object; which means the above is equivalent to:
final String dst = "/some/file";
final File f = new File(dst);
new FileOutputStream(f);
Conclusion: no, File*Stream does not know per se whether a file exists as long as it does not try to open it. Paths as well as Files are completely abstract until you try and do something with them.
And do yourself a favour: use the new file API which Java 7+ provides. Have you ever tried to initiate a FileInputStream with a File which exists but you cannot read from? FileNotFoundException. Meh. Files.newInputStream() will at least throw a meaningful exception...
Generally, you simply pass the file object to the stream instantiations.
FileInputStream is = new FileInputStream(f);
FileOutputStream os = new FileOutputStream(f);
BufferedInputStream is2 = new BufferedInputStream(is);
BufferedOutputStream os2 = new BufferedOutputStream(os);
Also consider using Printwriter for the output stream when you are working with text files.
About Streams:
Streams are objects that allow an app to communicate with other programs.
To directly answer your question, in Java, here is how I would use the Streams.
//You need to import a few classes before you begin
import java.io.FileInputStream;
import java.io.FileOutputStream;
You can declare them this way
FileInputStream is = new FileInputStream("filename.txt"); //this file should be located within the project folder
For output stream, it can be accessed a similar way:
FileOutputStream os = new FileOutputStream("filename.txt"); //this file should be located within the project folder
More Information:
I recommend using a PrintWriter when trying to write to text files. To do this, you would implement the following:
import java.io.PrintWriter;
Then use this to write to the file:
PrintWriter pw = new PrintWriter(OUTPUT_STREAM);
I also recommend using the Scanner class when reading in user data:
import java.util.Scanner;
Then use this to read the input:
Scanner kb = new Scanner(INPUT_STREAM); //now you can access this data by using methods such as nextInt, nextDouble, etc...

Categories

Resources