Read a XML file that's in the same directory - java

I know it's been asked before and answered, but i just can't make it work.
So, my files hierarchy is:
+ Project
+ build.xml
+ save.xml
+ src
+ build
I have the "save" file to save the state of a game in a given instant. It should be easy to overwrite and easy to read to load everything again in the game.
My save() is like this, and it seems to be working:
public void save(Game game) throws IOException{
Document doc = DocumentHelper.createDocument();
doc.add(game.save());
File save=null;
save = new File("./save.xml");
FileWriter writer = new FileWriter(save);
doc.write( writer);
writer.close();
}
game.save() is a method in the game that actually does what i want to do. It does it recursively and all, and i know it works fine because i opened the XML file with another program.
So, my problems begins here. My getinfofromxml() method is:
public Game getinfofromxml() throws IOException{
Game game;
SAXReader reader = new SAXReader();
try{
URL fileWithData=getClass().getResource("./save.xml");
Document document = reader.read(fileWithData);
Element alreadySavedGame= document.getRootElement();
game= getGameSaved(alreadySavedGame);
}catch(DocumentException ex){
throw new IOException();
}
return game;
}
My problem is, when try to run it (via ant), no test will pass. I go to eclipse, and i can see that when i try to load the game, it throws Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
I've tried changing the line URL fileWithData=getClass().getResource("./save.xml"); to URL fileWithData=getClass().getResource("save.xml"); and URL fileWithData=getClass().getResource("../save.xml"); and things like that, but it says always the same.
Any idea?
Thank you for reading

so, if you use getResource() it will try to find your file using the classloader that was used to load that class. this might be (later at least) the jar file your app is packaged in, and i don't think that's you're trying to load your savegame from there :)
i'd load the file the same way you save it:
URL fileWithData= new File( "save.xml" ).toURI().toURL();
(you might have to catch an extra exception)

Related

How to resolve java.nio.file.FileSystemException The process cannot access the file because it is being used by another process

I am getting the exception (java.nio.file.FileSystemException) while I run the this code
public String getScreenShotAsBase64() throws IOException {
File source = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String path = System.getProperty("user.dir") + "/Screenshots/image.png";
FileUtils.copyFile(source, new File(path));
byte[] imageBytes = IOUtils.toByteArray(new FileInputStream(path));
return Base64.getEncoder().encodeToString(imageBytes);
}
when I try to run the method it is not working throws exception.
The cause of your problem is that Windows won't let your application open the "Screenshots/image.png" file for writing because something else already has it open. It just won't. See File Locking for an overview of Windows file locks and their purpose.
This SuperUser Q&A gives a number of ways to figure out which other application holds the file lock:
Find out which process is locking a file or folder in Windows
Your use of Selenium in this instance is (probably) not apropos.
You will most likely need to do one of the following to resolve this.
Change your application to write the screenshot to another file if the first target file it chooses is locked.
Tell the user that your application can't write the file. The user message could suggest that they need to close whatever other application it is that has the image file open at the moment.
If the other application is Windows itself (for some reason) you will probably need to rethink what you trying to do.

Opening a File in java during run time

What i am trying to do is have my java create a vbs file, open the file to run it, than delete it. i have covered the creating and deleting part of it but what i am trying to do it run it, and since eventually the jar will be in random places i cant open it with an exact path. Anyone have any ideas on how to accomplish this? Here is what i have (simplified for reading)
public void MapDrive() throws IOException {
File map = new File("map.vbs");
map.createNewFile();
PrintWriter writer = new PrintWriter("map.vbs");
writer.println(" VBS code here ");
writer.close();
map.delete();
}

Creating a new directory inside Android internal memory and writing data to it

Most of the examples I have seen deal with external memory or show how to create a new directory inside internal memory but not how to write to it, I tried implementing my own code into it but can't seem to find the created file even though the directory has been created, here is the code that I have been trying to use:
public void fileCreate(Context context, String fileDir) throws Exception{
File myNewDir = context.getDir(fileDir, Context.MODE_PRIVATE);
if (!myNewDir.exists()){
myNewDir.mkdirs();
File testContnet = new File(myNewDir + "/hello_file.txt");
String hello = "Hello world";
FileOutputStream fos = openFileOutput(testContnet.toString(), Context.MODE_PRIVATE);
fos.write(hello.getBytes());
fos.close();
}
}
Now, when I call this function I use:
try {
fileCreate(this, "testerDirectory");
}catch(Exception e) {
e.printStackTrace();
}
With no results. It is just for a small experiment I am doing so it is nothing too serious, but I still want to know about the proper way of creating a directory(in this case one called testerDirectory, and saving the file to it, I believe that my code is wrong but I do not have much experience with this to know exactly where to go. The Android documentation did show me how to create and save files although in this case I am trying to merge that example with that of creating a new directory and saving a file to it. Any help/pointers would be greatly appreciated.
I know also that the file is not being written accordingly upon inspecting the contents of the directory by using the adb shell.
You are only writing a file to the directory if the directory does not already exist.
Move your work with testContnet to be outside of the if block:
public void fileCreate(Context context, String fileDir) throws Exception{
File myNewDir = context.getDir(fileDir, Context.MODE_PRIVATE);
if (!myNewDir.exists()){
myNewDir.mkdirs();
}
File testContnet = new File(myNewDir, "hello_file.txt");
String hello = "Hello world";
FileOutputStream fos = new FileOutputstream(testContnet);
fos.write(hello.getBytes());
fos.flush();
fos.getFD().sync();
fos.close();
}
This way, you create the directory if it does not exist, but then create the file in either case. I also added fos.flush() and fos.getFD().sync(), to ensure all bytes get written to disk before you continue.
UPDATE: You were using openFileOutput(), which does not write to your desired directory. Moreover, it is unnecessary. Just create a FileOutputStream on your File.

Where i Can find text file created by servlet in Eclipse

This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.

Load file dynamically from jar

I am trying to read a .json file I am packaging with my .jar.
The problem - finding the file so that I can parse it in.
The strange bit is that this code works in NetBeans, likely due to the way these methods work and the way NetBeans handles the dev workspace. When I build the jar and run it, however, it throws an ugly error: Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical.
My code for getting the file is as such:
//get json file
File jsonFile = new File(AndensMountain.class.getResource("/Anden.json").toURI());
FileReader jsonFileReader;
jsonFileReader = new FileReader(jsonFile);
//load json file
String json = "";
BufferedReader br = new BufferedReader(jsonFileReader);
while (br.ready()) {
json += br.readLine() + "\n";
}
I have gotten it to work if I allow it to read from the same directory as the jar, but this is not what I want - the .json is in the jar and I want to read it from in the jar.
I've looked around and as far as I can see this should work but it isn't.
If you are interested, this is the code before trying to get it to read out of the jar (which works as long as Anden.json is in the same directory as AndensMountain.jar):
//get json file
String path = AndensMountain.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
File jsonFileBuilt = new File(new File(path).getParentFile(), "Anden.json");
File jsonFileDev = new File(new File(path), "Anden.json");
FileReader jsonFileReader;
try {
jsonFileReader = new FileReader(jsonFileBuilt);
} catch (FileNotFoundException e) {
jsonFileReader = new FileReader(jsonFileDev);
}
Try
Reader reader = new InputStreamReader(AndensMountain.class.getResourceAsStream("/Anden.json"), "UTF-8");
AndensMountain.class.getResource("/Anden.json") URL when ran outside a jar (for example, when the classes are compiled to a "classes/" directory) is a "file://" URL.
That is not the case when ran from inside a jar: it then becomes a "jar://" URL.
The java.io.File doesn't know how to handle this type of URL. It handles only "file://".
Anyway you don't really need to treat it as a File. You can manipulate the URL itself (either to navigate to a parent directory, for example) or to get its contents (via openStream(), or if you need to add headers, via openConnection()).
java.lang.Class#getResourceAsStream() as I suggested is just shorthand to Class#getResource() followed by openStream() on its result.

Categories