I have created my sqlite database (employeertest.sql) and puted it in the Assets folder, then run
this code.
Unfortunately in the line getBaseContext().getAssets().open("employeertest") compiler says No such file or directory
try {
String destPath = "/data/data/" + getPackageName() +"/databases";
File f = new File(destPath);
f.mkdirs();
f.createNewFile();
//---copy the db from the assets folder into
// the databases folder---
CopyDB(getBaseContext().getAssets().open("employeertest"),
new FileOutputStream(destPath + "/employeertest"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Have you tried
CopyDB(getBaseContext().getAssets().open("employeertest.sql")
instead? Considering the file doesn't exist, I'm assuming the extension is missing and it cannot find the file.
you can use Context.getDatabasePath(String) to retrieve the correct path to the database directory. Please be aware that the directory could also not be there when you try to copy the db from the assets
Related
**I am trying to save and get Player objects from a Textfile and it works when using my IDE but when i create a Jar it can't find the text File. I tried with
this.getClas().getResources(path)
But still it didnt find the path to my text file.Can anybody Help?
public void setPlayer() throws FileNotFoundException {
ArrayList<Player> playerArrayList = new ArrayList<>();
playerArrayList = getPlayers();
Player player = new Player();
player.name = ViewManager.name;
player.score = Collision.points;
playerArrayList.add(player);
try{
FileOutputStream fileOut = new FileOutputStream("src/resources/highscore.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for(Player player1 : playerArrayList){
out.writeObject(player1);
}
out.close();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
ยดยดยดยด
Resource files are not physical Files, as they can be inside a jar. They are intended to be read-only, and the class loader may cache them. They are case sensitive, with / as path separator and there path starts at the class path's root, probably src/resources.
So use the resource file as fall back resource to copy, if some physical file does not exist.
Path appDir = Paths.get(System.getProperty("user.home") + ".myapp");
Files.createDirectories(appDir);
Path file = appDir.resolve("highscore.txt");
if (!Files.exists(file)) {
// Copy resource to file, either:
URL url = getClass().getResource("/highscore.txt");
Path templatePath = Paths.get(url.toURI());
Files.copy(templatePath, file);
// Or
InputStream templateIn = getClass().getResourceAsStream("/highscore.txt");
Files.copy(templateIn, file);
}
try (FileOutputStream out = Files.newOutputStream(file)) {
...
}
Path is the generalisation of File.
I don't know what IDE you're using, but you're writing the file to the source sub directory. That directory might not be included in the jar.
I just started to work with files today with Android and have been pulling my hair out all day. This throws a FileNotFoundException:
public void writeConfig(){
try {
File file = new File(Environment.getExternalStorageDirectory() + "/" + "AppName", "TimetableConfiguration");
if (!file.mkdirs()) {
P.rint("Couldn't create directory");
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(getActivity().getSharedPreferences("periods", MODE_PRIVATE).getString("periods", null).getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
P.rint("Didn't find file");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Any ideas?
I notice that instead of creating a file, it creates a child folder. Why is it doing this?
Thanks for any help :)
FileNotFoundException: Creates child folder instead of file
Yes. That is what you do.
You first create with mkdirs() a directory with a certain name.
After that you try to create a file with the same name which is impossible as there cannot be two files or directories with the same name.
So have a look and you will find that directory.
Well you had deduced most all yourself already. Now try to understand your code.
if (!file.mkdirs()) {
P.rint("Couldn't create directory");
You will see that printed every time you repeat the code. You should have seen this too. And have told us.
You should only call mkdirs if the directory does not exist yet.
Can someone please tell me if what I'm doing is correct?
File directoryToStore;
directoryToStore = getBaseContext().getExternalFilesDir("MyFiles");
Bitmap b = ThumbnailUtils.createVideoThumbnail(directoryToStore + "/" + SavedVideoName, 3);
File newFile = new File(directoryToStore, SavedVideoName.replace(".mp4", ".jpg"));
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(newFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
b.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
I'm trying create a thumbnail from a video, but for some the FileOutputStream returns null.
I have checked the path of File newFile = new File(directoryToStore, SavedVideoName.replace(".mp4", ".jpg")); and it returns the correct path.
The video exists at the location I have given and I have permissions. I can't understand why it is gives me a null pointer?
According to this post, new FileOutputStream() will try to create a new file if it doesn't exist already. From the docs:
If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.
When you are debugging (at least in Android Studio), if you add a breakpoint and hover over newFile, it shows the file path. However, it doesn't show any details about the file, because the file doesn't (shouldn't) exist yet. You could try newFile.createNewFile() as suggested in the linked post, to confirm you are able to write the file first.
Currently I'm developing a java application to carry out a survey. I want to read/write to a .txt file, creating a .csv to store inputted data. Below is code I have used so far to write data - Of course this makes the JAR file not portable as it has an absolute path.
File file = new File("C:/Files/JavaApp/src/text.text/");
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(file, true);
} catch (IOException e) {
System.out.println(e.getMessage());
}
bw = new BufferedWriter(fw);
try {
bw.write("blah" + ",");
} catch (IOException e) {
System.out.println(e.getMessage());
}
try {
bw.newLine();
} catch (IOException e) {
System.out.println(e.getMessage());
}
try {
bw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
I have tried several methods such as ClassName.class.getResource("Text.text"); but it will always return a Reflection or a NullPointer error.
I know that writing to a file within the JAR does pose some problems, meaning I would have to point to a file outside to read/write. However I don't know how to preform this in code. I need the JAR file to be completely portable. Even if that means it must be kept within a directory, so the JAR can search for the .txt file within that directory. Or, is there another way?
If anyone can help me out, I would be very grateful.
To read from the Jar file: How to read a file from jar in Java?
The file is an archive file. It is a zip file with a .jar extension. You shouldn't be writing to it. If the jar file has been signed (security projected) you cannot write to it. Changing a single bit in the file will invalidate it.
What you should do is store a default file in Jar and load that to the "user.home" folder if it is not already there.
Couldn't find too much about how to read a file that isn't somewhere on the SD card or storage, but rather right there in the android project directory.
I keep getting a FileNotFoundException. This is how I declare the file,
File SPPolicy = new File("SHPR_policy");
I've gotten the same error when putting it in the src/ directory, the src/[[package]]/ directory and the main project directory, and I get this error:
java.io.FileNotFoundException: /SHPR_policy: open failed: ENOENT (No such file or directory)
Is there a certain place I have to put this file? Is it because my file doesn't have an extension (I noticed the "/" before SHPR_policy but I didn't think it would be a problem because Eclipse let me create a file without an extension)?
Save the file in raw folder and try the below code.
try
{
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.test);
byte[] b = new byte[in_s.available()];
in_s.read(b);
txtHelp.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
txtHelp.setText("errr.");
}
Use these piece of code to check if the file was already created:
File f;
f=new File("myfile");
if(!f.exists()){
f.createNewFile();
}
Also, if you want to allocate your file in the external directory you can use these code:
File newxmlfile = new File( Environment.getExternalStorageDirectory() + "/new.xml");
XmlSerializer serializer = Xml.newSerializer();
try {
newxmlfile.createNewFile();
} catch (Exception e) {
Log.e("IOException", "exception in createNewFile() method", e);
}
And, did you added the permission in the manifest to be able to manipulate files?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You should place the file in the assets folder and use this:
InputStream ims = getAssets().open("SHPR_policy");