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
Related
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.
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();
is there a way to open a directory stream in Java like in C? I need a FileDescriptor of an opened directory. Well, actually just the number of the fd.
I try to implement a checkpoint/restore functionality in Java with the help of CRIU link. To do this, I need to deploy a RPC call to the CRIU service. There I have to provide the integer value of the FD of an already opened directory, where the image files of the process will be stored.
Thank you in advance!
is there a way to open a directory stream in Java like in C?
No there isn't. Not without resorting to native code.
If you want to "read" a directory in (pure) Java, you can do it using one of the following:
File.list() - gives you the names of the directory entries as strings.
File.list(FilenameFilter) - ditto, but only directory entries that match are returned.
File.listFiles() - like list() but returning File objects.
etcetera
Files.newDirectoryStream(Path) gives you an iterator for the Path objects for the entries in a directory.
The last one could be "close" to what you are trying to achieve, but it does not entail application code getting hold of a file descriptor for a directory, or the application doing a low-level "read" on the directory.
You don't need FD in Java. All you need is a reference to that file which you can simply acquire using File file = new File("PathToYourFile");
To read/write you have Streams in Java. You can use
BufferedReader fileReader = new BufferedReader(new FileReader(new File("myFile.txt")));
PrintWriter fileWriter = new PrintWriter(new FileWriter(new File("myFile.txt")));
Even directory is a file. You can use isDirectory() on file object to check if it is a directory or a file.
private FileDescriptor openFile(String path)
throws FileNotFoundException, IOException {
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file);
// remember th 'fos' reference somewhere for later closing it
fos.write((new Date() + " Beginning of process...").getBytes());
return fos.getFD();
}
I wounder how to make .ini file in Java. I know how to make .txt file, but how to make .ini file I don't. For reading and wrting I use ini4j lib and I thnik it works good. First I make some directory because of saving some data from user, then I want to make file and I get error java.io.FileNotFoundException for codeline ini.load(new FileReader(INI_PATH)); , that means that my code doesn't make .ini file in codeline File newFile = new File(newPath+"connect.ini"); . Please help me!
My code is:
String path =System.getProperty("user.home");
dir = new File(path+"/ProjectName");
String newPath=path+"/ProjectName";
if(dir.exists()){
System.out.println("DIRECTORY EXISTS");
}
else{
dir.mkdir();
}
newPath=newPath+"/";
File newFile = new File(newPath+"connect.ini");
INI_PATH = newFile.getAbsolutePath();
System.out.println("INI_PATH "+INI_PATH);
Wini ini = new Wini();
ini.load(new FileReader(INI_PATH));
...SOME CODE FOR ADDUING PAIRS....
You are getting a FileNotFoundException because the file does not exist on the disk, if you are trying to create the file in code use the following:
File newFile = new File(newPath+"connect.ini");
newFile.createNewFile();
the createNewFile() method on Java's File class will create a file if it doesn't exist, then you can feel free to use a FileReader or FileWriter to work with the newly created (but blank) file.
I can read texts and write them to console however when i install this application to another computer wherever it is installed I dont want to change the path of the txt file. I want to write it like
BufferedReader in = new BufferedReader(new FileReader("xxx.txt"));
I don't want to:
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\abcde\\Desktop\\xxx.txt"));
is there any way to show this txt file? By the way I put this txt file inside the sources but it cant read!
First get the default application path then check if file exist if exist continue if not close application.
String path = System.getProperty("user.dir");
System.out.println(path + "\\disSoruCevap.txt");
File file = new File(path + "\\disSoruCevap.txt");
if (!file.exists()) {
System.out.println("System couldnt file source file!");
System.out.println("Application will explode");
}
EDIT*
Please prefer one of the answer using resource streams, as you will
see from comments using user.dir is not safe in every case.
You are looking for :
BufferedReader in = new BufferedReader(getClass().getResourceAsStream("/xxx.txt"));
This will load xxx.txt from your jar file (or any jar file in your class path that has that file inside its root directory).
URL fileURL= yourClassName.class.getResource("yourFileName.extension");
String myURL= fileURL.toString();
now you don't need long path name PLUS this one is dynamic in nature i.e., you can now move your project to any pc, any drive.This is because it access URL by using your CLASS location not by any static location (like c:\folder\ab.mp3, then you can't access that file if you move to D drive because then you have to change to D:/folder/ab.mp3 manually which is static in nature)(NOTE: just keep that file with your project)
You can use fileURL as: File file=new File(fileURL.toURI());
You can use myURL as: Media musicFile=new Media(myURL); //in javaFX which need string not url of file
InputStream input = Class_name.class.getResourceAsStream("/xxx.txt");
InputStreamReader inputReader = new InputStreamReader(input);
BufferedReader br = new BufferedReader(inputReader);
String line = null;
try {
while((line = br.readLine())!=null){
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
You don't need to write or mention long path. Using this code Class_name.class.getResourceAsStream("/xxx.txt"), you can easily get your file.
BufferedReader in = new BufferedReader(new FileReader("xxx.txt")); works fine because when you run your application on an IDE, xxx.txt apparantly is lying in Java's working directory.
Working directory is an operating system feature and it can not be changed.
There are a few ways to deal with this.
1 - use file constructor new File(parent, filename); and load parent using a public static final constant or a property (either passed from command line or otherwise)
2 - or use InputStream in = YourClass.class.getClassLoader().getResourceAsStream("xxx.txt"); - provided your xxx.txt file is packaged under same location as YourClass
Try:
InputStream is = ClassLoader.getSystemResourceAsStream("xxx.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
Depending on where exactly is your file compared to the root of your classpath, you may have to replace xxx.txt3 with /xxx.txt.
My file paths are like this:
public final static String COURSE_FILE_LOCATION = "src/main/resources/courses.csv";
public final static String PREREQUISITE_FILE_LOCATION = "src/main/resources/prerequisites.csv";
This doesn't work. So I delete the .iml file, .idea and target folder from the project and reload them.
Read the correct path like this:
This would work then.