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");
Related
I've been trying to save text to a file in the documents folder in internal storage to be accessed by file manager so i can read it, I've tried several methods including using a writer, but I can't seem to get it to work, I'm not trying to save to external storage, I don't have external storage, only internal, and that's where my documents folder is, so I'm assuming I don't have to bother with the permissions in manifest, I threw in the setReadable just in case but I still can't find it in the documents folder, this is where I'm currently at.
public void writeToFile(String string){
try {
File file = new File(Environment.DIRECTORY_DOCUMENTS, "myFile.txt");
file.setReadable(true);
FileOutputStream stream = new FileOutputStream(file);
stream.write(string.getBytes(string));
stream.flush();
stream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
File file = new File(Environment.DIRECTORY_DOCUMENTS, "myFile.txt");
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "myFile.txt");
I need to open a video file with my code, and it works perfectly fine in Eclipse but when I export into a runnable JAR, i get an error "URI not hierarchical".
I have seen people suggest using getResourceAsStream(), but i need to have a file object as i am using Desktop.getDesktop.open(File). Can anyone help me out?
Here is the code:
try {
URI path1 = getClass().getResource("/videos/tutorialVid1.mp4").toURI();
File f = new File(path1);
Desktop.getDesktop().open(f);
} catch (Exception e) {
e.printStackTrace();
}
if it helps my folder list is like
Src
videos
videoFile.mp4
EDIT:
I plan to run this on windows only, and use launch4j to create an exe.
You can copy the file from the jar to a temporary file and open that.
Here's a method to create a temporary file for a given jar resource:
public static File createTempFile(String path) {
String[] parts = path.split("/");
File f = File.createTempFile(parts[parts.length - 1], ".tmp");
f.deleteOnExit();
try (Inputstream in = getClass().getResourceAsStream(path)) {
Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
return f;
}
And here's an example of how you'd use it:
Desktop.getDesktop().open(createTempFile("/videos/tutorialVid1.mp4"));
Is there any way to create a folder structure inside of the local DCIM folder of an Android phone?
Android 5.1
I need to create the next folder structure.
DCIM/Camera/Notes
and create a file there.
I do the next:
File internalDcimDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
internalDcimDir = new File(internalDcimDir, "Camera");
internalDcimDir = new File(internalDcimDir, "Notes");
internalDcimDir.mkDirs();
And when I try to create a file no exceptions occure
File file = new File(internalDcimDir, noteFileName);
And when I write something..
FileOutputStream outputStream = null;
try {
OutputStream fo = new FileOutputStream(file);
fo.write(content.getBytes());
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
it occures that there is no file and even dirs created.
May be I am doing something wrong. What can it be?
File file1 = new File(file.getAbsoluteFile() + "/example/directory/example.png");
file1.mkdirs();
file1.setWritable(true);
file1.createNewFile();
try {
FileInputStream is = new FileInputStream(exampleInputDirectory);
FileOutputStream os = new FileOutputStream(file1);
FileChannel srcChannel = is.getChannel();
FileChannel dstChannel = os.getChannel();
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
This is my setup for copying an image file to a new directory tree. However, when this code is executed I get the following:
java.io.FileNotFoundException: *points to output directory* (Access is denied)
Have I gone about creating file1 incorrectly?
The problem here is because of using
file1.mkdirs();
and
file1.createNewFile();
together.
Since the file1 object is already been given 'directory' attributes after creating it as directory by calling "file1.mkdirs()", but then you are again using the same object to create a 'file', that means changin attribute of file1 object from directory to a file, which is not allowed. that's why its giving you FileNotFound.
Your creation of file1 seems to be up to par, maybe your input dir is non existent? Make sure all caps and such are correct, and that there are no typos in your directory reference. Also be sure if the user has permissions to copy a file to the directory, if not you can run it as root in linux, and as administrative in windows.
I want to programmatically access a specific file which will be included in my project folder. Is there a way to do this? If so, where in my project folder do I put the file, and what is some simple code to get its file path?
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
java.io.File spreadsheet = new java.io.File("Untitled spreadsheet.xlsx");
String filePath = spreadsheet.getAbsolutePath();
System.out.println("file path is"+filePath);
URL fileURL = getClass().getClassLoader().getResource("Untitled spreadsheet.xlsx");
String filePath2 = fileURL.getPath();
System.out.println("file path2 is"+filePath2);
java.io.File fileContent = new java.io.File(filePath);
FileContent mediaContent = new FileContent("application/vnd.ms-excel", fileContent);
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("application/vnd.ms-excel");
File file = service.files().insert(body, mediaContent).setConvert(true).execute();
if (file != null) {
showToast("File uploaded: " + file.getTitle());
}
else
;
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
Put the file in root folder of your project. Then get the File URL, Path and other details as:
File file = new File("test.txt");
String filePath = file.getAbsolutePath();
EDIT: Alternate way (if the file is in your classpath e.g. put the file in "src" folder, and make sure its moved in "bin" or "classes" folder after compilation):
URL fileURL = getClass().getClassLoader().getResource(fileName);
String fileName = fileURL.getFile();
String filePath = fileURL.getPath();
This depends a lot on what type of file you want to access. You can put the file in either assets or an appropriate subdirectory of res (see Difference between /res and /assets directories).
So you want to access a file internal to your app; and you want to do so directly, rather, that is, from an Android Context (and then with a [android.|<package_name>.]R.<resource_type>.<resource_name>).
You have two choices as to location: the res/raw folder or assets/ folder (outside of the res parent).
To choose between the two note from https://developer.android.com/guide/topics/resources/providing-resources.html
Arbitrary files to save in their raw form. To open these resources with a raw InputStream, call Resources.openRawResource() with the resource ID, which is R.raw.filename.
However, if you need access to original file names and file hierarchy, you might consider saving some resources in the assets/ directory (instead of res/raw/). Files in assets/ aren't given a resource ID, so you can read them only using AssetManager.
To access a file in res/raw/ directly rather, that is, from an Android Context (and then with a [android.|<package_name>.]R.<resource_type>.<resource_name>) you can do something like this:
File file = new File("app/src/main/res/raw/country_data_from_world_bank.xml");
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));