Create a public folder in internal storage - java

Sorry for my English, but I want to write in this file because in my opinion is the best.
Now my problem:
I want to create a folder in Internal storage to share with 2 application.
In my app, I downloaded an Apk from my server and I run it.
Before I used external storage and everything worked.
Now I want to use the internal storage for users that don't have an external storage.
I use this:
String folderPath = getFilesDir() + "Dir"
but when i try to run the Apk, it doesn't work, and I can't find this folder on my phone.
Thank you..

From this post :
Correct way:
Create a File for your desired directory (e.g., File path=new
File(getFilesDir(),"myfolder");)
Call mkdirs() on that File to create the directory if it does not exist
Create a File for the output file (e.g., File mypath=new File(path,"myfile.txt");)
Use standard Java I/O to write to that File (e.g., using new BufferedWriter(new FileWriter(mypath)))
Enjoy.
Also to create public file I use :
/**
* Context.MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application.
* Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.
*/
public static void createInternalFile(Context theContext, String theFileName, byte[] theData, int theMode)
{
FileOutputStream fos = null;
try {
fos = theContext.openFileOutput(theFileName, theMode);
fos.write(theData);
fos.close();
} catch (FileNotFoundException e) {
Log.e(TAG, "[createInternalFile]" + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "[createInternalFile]" + e.getMessage());
}
}
Just set theMode to MODE_WORLD_WRITEABLE or MODE_WORLD_READABLE (note they are deprecated from api lvl 17).
You can also use theContext.getDir(); but note what doc says :
Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory. Note that files created through a File object will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
Best wishes.

You can create a public into a existing system public folder, there is some public folder accessible from internal storage :
public static String DIRECTORY_MUSIC = "Music";
public static String DIRECTORY_PODCASTS = "Podcasts";
public static String DIRECTORY_RINGTONES = "Ringtones";
public static String DIRECTORY_ALARMS = "Alarms";
public static String DIRECTORY_NOTIFICATIONS = "Notifications";
public static String DIRECTORY_PICTURES = "Pictures";
public static String DIRECTORY_MOVIES = "Movies";
public static String DIRECTORY_DOWNLOADS = "Download";
public static String DIRECTORY_DCIM = "DCIM";
public static String DIRECTORY_DOCUMENTS = "Documents";
To create your folder, use this code :
File myDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MyPublicFolder");
myDirectory.mkdir();
With this example, a public will be created in Documents and can be visible in any file's explorer app for Android.

try the below
File mydir = context.getDir("Newfolder", Context.MODE_PRIVATE); //Creating an internal dir;
if(!mydir.exists)
{
mydir.mkdirs();
}

This is what i have used and is working fine for me:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, fileName);
File parent=file.getParentFile();
if(!parent.exists()){
parent.mkdirs();
}
This will create a new directory if not already present or use the existing if already present.

Related

Access public assets with Java in Play Framework

Is it possible to access Assets inside the Java code in Play Framework? How?
We access assets from the scala HTML templates this way:
<img src="#routes.Assets.versioned("images/myimage.png")" width="800" />
But I could not find any documentation nor code example to do it from inside the Java code. I just found a controllers.Assets class but it is unclear how to use it. If this is the class that has to be used, should it maybe be injected?
I finally found a way to access the public folder even from a production mode application.
In order to be accessible/copied in the distributed version, public folder need to be mapped that way in build.sbt:
import NativePackagerHelper._
mappings in Universal ++= directory("public")
The files are then accessible in the public folder in the distributed app in production form the Java code:
private static final String PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH = "public/images/";
static File getImageAsset(String relativePath) throws ResourceNotFoundException {
final String path = PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH + relativePath;
final File file = new File(path);
if (!file.exists()) {
throw new ResourceNotFoundException(String.format("Asset %s not found", path));
}
return file;
}
This post put me on the right way to find the solution: https://groups.google.com/forum/#!topic/play-framework/sVDoEtAzP-U
The assets normally are in the "public" folder, and I don't know how you want to use your image so I have used ImageIO .
File file = new File("./public/images/nice.png");
boolean exists = file.exists();
String absolutePath = file.getAbsolutePath();
try {
ImageInputStream input = ImageIO.read(file); //Use it
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("EX = "+exists+" - "+absolutePath);

Android app: How do I create a directory in the internal storage

I can't seem to be able to figure out how to create a directory/file through an android app to the internal storage. I have the following code:
public class Environment extends SurfaceView implements SurfaceHolder.Callback {
public static String FILE_PATH;
//other unimportant variables
public Environment(Conext context) {
super(context);
FILE_PATH = context.getFilesDir() + "/My Dir/";
File customDir = new File(FILE_PATH);
if(!customDir.exists())
System.out.println("created my dir: " + customDir.mkdir());
File test = new File(FILE_PATH + "testFile.txt");
try {
if(!test.exists())
System.out.println("created test: " + test.createNewFile());
} catch(Exception e) {
e.printStackTrace();
}
//other unimportant stuff
}
}
I then use ES File Explorer to see if it created the file and I don't see the directory/file anywhere despite it printing out "true" for the System.out.println() calls.
What am I doing wrong?
The path where you are creating file is in apps private location. Generally you can't access it from outside. It's actually created in apps data folder. However it seems you want to write in external folder.
To write in the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
code:
String folder_main = "My Dir";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
File test = new File(f , "testFile.txt");
Here you will find how to you will create folder/file in external storage.
Save a File on External Storage
You can try with below:
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(getFilesDir().getName(), Context.MODE_PRIVATE);
File file = new File(directory,”fileName”);
String data = “TEST DATA”;
FileOutputStream fos = new FileOutputStream(“fileName”, true); // save
fos.write(data.getBytes());
fos.close();
This will write file in Device's internal storage (/data/user/0/com.yourapp/)
Hope this helps!

Written file not appearing in external directory [duplicate]

My app should save files to a place where, when you connect your phone/tablet to a computer, you can see them through the system file explorer.
This is the way I implemented file writing:
protected String mDir = Environment.DIRECTORY_DOCUMENTS;
protected File mPath = Environment.getExternalStoragePublicDirectory(mDir);
protected void writeLogFile(String filename) {
File f = new File(mPath, filename + ".txt");
f.getParentFile().mkdirs();
try (BufferedWriter bw = new BufferedWriter(new FileWriter(f, false))) {
// Details omitted.
} catch (Exception e) {
e.printStackTrace();
return;
}
makeText("Wrote " + f.getAbsolutePath());
}
This is what I see when I connect my Sony Xperia Z4 tablet to Windows (notice missing documents folder):
This is the directory to which the file is written (using above implementation):
What is wrong with my implementation?
What is wrong with my implementation?
MediaStore has not discovered your newly-created files yet. What you see in Windows — and in many on-device "gallery" apps — is based on what MediaStore has indexed.
Use MediaScannerConnection and its scanFile() method to tell MediaStore about your file, once you have written out your data to disk:
public void scanFile(Context ctxt, File f, String mimeType) {
MediaScannerConnection
.scanFile(ctxt, new String[] {f.getAbsolutePath()},
new String[] {mimeType}, null);
}
or, in Kotlin:
fun scanFile(ctxt: Context, f: File, mimeType: String) {
MediaScannerConnection.scanFile(ctxt, arrayOf(f.getAbsolutePath()), arrayOf(mimeType), null)
}

Unix executable changes to TextEdit document when copied

I have the following script, of which you can see below. The function of this Java script is to copy a Mac app, of which is placed in the same folder as the java program. It first finds the path of the folder, which the app and java program is in. It then copies all the content to the documents folder on the Mac device. When that is done it is then supposed to run that app of which it has copied to the documents folder.
The only issue is that it isn't able to do so. The reason being that whenever it copies the app, the JavaAppLauncher which is found within the content of the mac app has changed from a unix executable to a regular TextEdit document and thus can't actually launch the app. However if I were to copy the app manually by copying it myself and not using the java program, there is no issue. I am not sure whether this issue is caused by my code, or whether it is just a general thing?
Important note, the .app does work when I just run the regular non copied version, but as soon as it is the copied version, which as been copied through Java it doesn't work because the change of the Unix executable.
public class LaunchProg {
static String usernameMac2 = System.getProperty("user.name");
static File propFile = new File (".");
static String pathString = propFile.getAbsolutePath();
static int pathhLeng = pathString.length();
static int pathReaLeng = pathhLeng -1;
static String filNamMac = "AppNam.app";
static String pFPathRelMac = pathString.substring(0,pathReaLeng);
private static final File fSourceMac = new File(pFPathRelMac);
private static final File AppFold = new File ("/Users/" + usernameMac2 + "/Documents");
static File fileCret = new File("fCret.txt");
public static void main(String[] args) throws IOException {
System.out.println(pFPathRelMac);
launchMac();
}
static void launchMac() throws IOException {
if (!fileCret.exists()){
try {
FileUtils.copyDirectory(fSourceMac, AppFold);
PrintWriter pFW = new PrintWriter(fileCret);
pFW.println("Created File For Check");
pFW.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
String command = "open /Users/" + usernameMac2 + "/Documents/AppNam.app";
Process staAp2 = Runtime.getRuntime().exec(command);
}
}
}
}

Include local .json file in Eclipse Android project

I have a local .json file. I don't want it to be on a server, I just want it to be included in my app. I tried to paste it directly into Eclipse in my project, but I got a FileNotFoundException, I also tried to paste it in the workspace folder in Windows Explorer/Finder and got the same exception. Where should I put it?
Thanks!
You should put the file either in the /assets or /res/raw directory of your Android project. From there, you can retrieve it with either: Context.getResources().openRawResource(R.raw.filename) or Context.getResources().getAssets().open("filename").
Put the json file in assets folder, I have used this method like this
public static String jsonToStringFromAssetFolder(String fileName,Context context) throws IOException {
AssetManager manager = context.getAssets();
InputStream file = manager.open(fileName);
byte[] data = new byte[file.available()];
file.read(data);
file.close();
return new String(data);
}
While parsing we can use the method like:
String jsondata= jsonToStringFromAssetFolder(your_filename, your_context);
jsonFileToJavaObjectsParsing(jsondata); // json data to java objects implementation
More Info: Prativa's Blog
Put the file in the assets folder.
You can use the AssetManager open(String fileName) to read the file.
Under /assets in your project folder. If you don't have one, make it.
Copy Asset to Local Storage
I had a very similar need. I had a label template file that I needed to provide a Bluetooth printer configuration so I included it in my assets directory and copied it to the internal storage for later use:
private static final String LABEL_TEMPLATE_FILE_NAME = "RJ_4030_4x3_labels.bin";
InputStream inputStreamOfLabelTemplate = getAssets().open( LABEL_TEMPLATE_ASSET_PATH );
labelTemplateFile = new File( getFilesDir() + LABEL_TEMPLATE_FILE_NAME );
copyInputStreamToFile( inputStreamOfLabelTemplate, labelTemplateFile );
printer.setCustomPaper( labelTemplateFile.getAbsolutePath() );
copyInputStreamToFile Function
// Copy an InputStream to a File.
//
private void copyInputStreamToFile(InputStream in, File file) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Categories