How to create Directory and See it on Computer - java

I try to create directory on Tablet and want to see it.
I create directory with this code
public void createDirectory(String sDirectoryName) {
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
File fileWithinMyDir = new File(direct, "myfile");
if(!direct.exist()) {
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
}
I see everytime Directory created, But when I search Folder in file system, I can not see it. How can I make it visible. Am I making wrong?
EDIT:
I gave all permission on manifest. And I tried this code too
File direct = new File(Environment.getExternalStorageDirectory()+"/"+sDirectoryName);
if(!direct.exists())
{
if(direct.mkdir())
{
System.out.println("Directory created");
Toast.makeText(MainActivity.this, "Directory created", Toast.LENGTH_LONG).show();
}
else
{
System.out.println("Directory not created");
Toast.makeText(MainActivity.this, "Directory not created", Toast.LENGTH_LONG).show();
}
}
But this is not working for me too.
EDIT:
For refreshing I use this code.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
working.

Note: because Android uses the MTP protocol for USB connections sometimes a file or folder just wont show because everything is cached and may need a refresh.
More info: Nexus 4 not showing files via MTP

File does not create a file if it doesn't exist. It just stores the path to it. Your if statement shows it doesn't exist.

Try this...
public void createDirectory(String sDirectoryName)
{
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), sDirectoryName);
if (!file.exists()) {
file.mkdirs();
}
}

Use below code to create directory.
public void createDirectory(String sDirectoryName) {
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
File fileWithinMyDir = new File(direct, "myfile");
if(!direct.exist()) {
direct.mkdirs();
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
}
Add permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Make sure that your manifeist have the following permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And in code
File directory = new File(Environment.getExternalStorageDirectory()+DOC_FOLDER_NAME);
// create directory if not exists
if(!directory.exists())
{
if(directory.mkdirs()) //directory is created;
Log.i(" download ","App dir created");
else
Log.w(" download ","Unable to create app dir!");
}

To create a dir:
if(!direct.exist()) {
if (direct.mkdir())
Log.i(TAG, "Directory created");
else
Log.w(TAG, "Failed to create directory");
}
and don't forget permissions in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Your print statement is confusing :
if(!direct.exist()) { // If directory does not exist
System.out.println("Directory created"); // Directory created not true
}
As just creating a File object it will not create directory the code should be:
if(!direct.exist()) { // If directory does not exist
direct.mkdir(); // Create directory
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
Also make sure to add android.permission.WRITE_EXTERNAL_STORAGE permission in your application.
Additionally its suggested not to use System.out.println in Android as On the emulator and most devices System.out.println gets redirected to LogCat and printed using Log.i(). This may not be true on very old or custom Android versions.

in manifest add this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and this for java file:
File myDirectory = new File(Environment.getExternalStorageDirectory(), "dirName");
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}
to delete it:
myDirectory.delete();
and this for File object for the parent directory:
//create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);

Is the issue not on the line
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
According to the documentation context.MODE_PRIVATE will only be visible within the app itself another program or user ID won't be able to find it.
try:
File direct = getDir(sDirectoryName, Context.MODE_WORLD_READABLE);
or
File direct = getDir(sDirectoryName, Context.MODE_WORLD_WRITEABLE);
http://developer.android.com/reference/android/content/Context.html

Related

Unable to open excel file on Android using Intent.ACTION_VIEW

I'm trying to let a user export an excel file in my app and have the app automatically open the created excel file. The excel file is created and stored successfully using jxl, but when I try to open it with the Hancom Office Editor nothing happens other than my screen getting a dark overlay. Here's a gif:
I can't figure out what would cause this and can't find anything about it online.
I'm using the accepted answer from here to support my target SDK 28.
my export method:
public void onExport(View view){
try {
//write changes to excel file(changes made outide of function)
workbook.write();
workbook.close();
Toast.makeText(getApplication(),
"Data Exported to Excel Sheet", Toast.LENGTH_SHORT).show();
findViewById(R.id.btn_export).setEnabled(false);
//set file to saved excel file
File file = new File(Environment.getExternalStorageDirectory(),
race.getName()+".xls");
Uri path = FileProvider.getUriForFile(getApplicationContext(), "com.something.racecalculator.fileprovider", file);
Intent intent = new Intent(Intent.ACTION_VIEW);
Log.i("path: ", path.toString());
intent.setDataAndType(path, "image/jpg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
catch (ActivityNotFoundException e) {
Log.i("oh no:", "No application available to view excel");
}
}
My provider tag in AndroidManifest.xml(set as a child of ):
<provider
android:name=".GenericFileProvider"
android:authorities="com.something.racecalculator.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
I'm not getting any Errors or warnings as far as I can tell. Thanks for any help.
I'm not sure exactly what caused the problem, however, I suspect that I might have had the file path wrong. I changed a couple things (including where the excel files were being saved to. Changed from /storage/emulated/0/ to /storage/emulated/0/Samsung) and here is what worked:
Intent intent = new Intent(Intent.ACTION_VIEW);
File file = new File("/storage/emulated/0/Samsung"+File.separator + race.getName()+".xls");
Uri path = FileProvider.getUriForFile(getApplicationContext(), "com.something.racecalculator.fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(path, "application/vnd.ms-excel");
startActivity(intent);
remember that you need to implement a FileProvider if your target SDK is 24 or above

Java android delete File

I want to delete a file (pdf file) I did this :
boolean deleted = filesList.get(pos).delete();
But when I look in my phone I see this file , but my application doesn't see this file
To delete a file from a directory, you can use this method:
public static void deleteFile(File directory, String fileName) {
if (directory.isDirectory()) {
for(File file : directory.listFiles()) {
if (file.getName().contains(fileName)) {
if (file.isFile()) {
if (file.exists()) {
file.delete();
}
}
}
}
}
}
And if you want to delete the entire directory:
public static void deleteDirectory(File directory) {
if (directory.isDirectory())
for (File child : directory.listFiles())
deleteDirectory(child);
directory.delete();
}
As mentioned by ylmzekrm1223, you should provide permissions to read and write storage in your AndroidManifest.xml, before attempting to delete a file or a directory.
Your code doesn't delete a file from the file system. It just deletes an element from the list.
Check this for more
delete file in sdcard
To delete a file from the file system, first you need to provide Permission to read and write local storage in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Then, in your code,
String path = "/mnt/sdcard/test.pdf";
File mFile = new File(path);
mFile.delete();

Read from file but I didn't see in android?

I want to read from txt file and send to TextView. My method works on Java Project I read and I see System.out.print but the same method doesnt work in MainActivity. How can I fixed.Thanks
MainActivity
public class MainActivity extends Activity {
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=(TextView)findViewById(R.id.textView1);
Parsing p =new Parsing();
try {
String gelen=p.readTxt();
txt.setText(gelen);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Parsing:
public class Parsing {
public String readTxt() throws FileNotFoundException
{
File file = new File("C:\\Users\\John\\Desktop\\try.txt");
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
}
I'm working it but I see just TextView.
you cannot specify the computer directory files to the android file path location to read lines in it.
just put the file into your android project folder like assests and change the
path and then try.
How can I read a text file in Android?
I don't mean to be rude but try to search first. This question with similar problem was already asked.
I hope this link will help you.
Cheers
For file on sdcard ("sdcard\myfolder\1.txt") please use:
File file = new File(Environment.getExternalStorageDirectory(), "myfolder\1.txt");
Also dont forget:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You must put the file in the asset folder of your project.
Then to access it you can do something like
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
for more details read my answer here :
read file from assets
First of all Android Application Project is different from Java Project.
You can not use File file = new File("C:\\Users\\John\\Desktop\\try.txt"); in android.
Place your text file in the /assets directory under the Android project. Use AssetManager class to access it.
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
If you are going to access file from memory card, Then use inputsteram is in your program. Also you need the following permission to read the text file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

How to use zip4j to extract an zip file with password protection

I am trying to unzip a zipfile with password protection. I know there is a java library named "zip4j" that could help me. But I am failing to open the zip4j website to see the tutorial.
I had download zip4j library with another mirror but I don't know how to use it. Is there anyone that could paste example code for using zip4j unzip password protection zip file?
zip4j website
thanks so much!
Try the following and make sure you are using the most recent Zip4j library (1.3.1):
String source = "folder/source.zip";
String destination = "folder/source/";
String password = "password";
try {
ZipFile zipFile = new ZipFile(source);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destination);
} catch (ZipException e) {
e.printStackTrace();
}
Here we have a file game.zip in Downloads folder in android phone and we are extracting it with the password given below:
String unzipFileAddress = Environment.DIRECTORY_DOWNLOADS "/Game.zip";
String filePassword = "2222"; // password of the file
String destinationAddress = Environment.DIRECTORY_DOWNLOADS + "/Game";
ZipFile zipFile = new ZipFile(unzipFileAddress, filePassword.toCharArray());
try {
zipFile.extractAll(destinationAddress);
} catch (Exception e) {
// if crashes print the message or Toast
}
Add in dependencies in build Gradle (app level) before doing it
dependencies{
implementation 'net.lingala.zip4j:zip4j:2.6.4'
} // for lastest version check the link below
Make sure you have storage permission, these silly mistakes can take your valuable time
// Add in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Make sure your zip file is not a corrupt file by extracting it manually.
If you want to do some complex work with compression, you should take help from here: https://github.com/srikanth-lingala/zip4j
Full Implementation to Zip/Unzip a Folder/File with zip4j
Add this dependency to your build manager. Or, download the latest JAR file from here and add it to your project build path. The class bellow can compress and extract any file or folder with or without password protection-
import java.io.File;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import net.lingala.zip4j.core.ZipFile;
public class Compressor {
public static void zip (String targetPath, String destinationFilePath, String password) {
try {
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
if (password.length() > 0) {
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword(password);
}
ZipFile zipFile = new ZipFile(destinationFilePath);
File targetFile = new File(targetPath);
if (targetFile.isFile()) {
zipFile.addFile(targetFile, parameters);
} else if (targetFile.isDirectory()) {
zipFile.addFolder(targetFile, parameters);
} else {
//neither file nor directory; can be symlink, shortcut, socket, etc.
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void unzip(String targetZipFilePath, String destinationFolderPath, String password) {
try {
ZipFile zipFile = new ZipFile(targetZipFilePath);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destinationFolderPath);
} catch (Exception e) {
e.printStackTrace();
}
}
/**/ /// for test
public static void main(String[] args) {
String targetPath = "target\\file\\or\\folder\\path";
String zipFilePath = "zip\\file\\Path";
String unzippedFolderPath = "destination\\folder\\path";
String password = "your_password"; // keep it EMPTY<""> for applying no password protection
Compressor.zip(targetPath, zipFilePath, password);
Compressor.unzip(zipFilePath, unzippedFolderPath, password);
}/**/
}
For more detailed usage, see here.
If you are working on android, then please make sure that you have added storage permission in the manifest file.

Reading files inside a APK

I am having an android application that is using an external jar that
has in addition to regular classes an html file.
Meaning my final apk root directory looks something like this
assests
res
AndroidManifest.xml
classes.dex
resources.arsc
helloworld.html
How can I access from my application to the last file
"helloworld.html"?
Android package hierarchy is not a like java application package.
So you can't access files like this.
I think you have to use this helloworld.html file in your application.
So put this file in /asset directory and in your activity code just get file using
getAssets().
also access file like: file:///android_asset/helloworld.html
Why not making a library project instead of a jar?
You have to replace the string "assets/SecureManifest.xml" with your file "helloworld.html"
public static InputStream getInputStreamFromApkResource(String apkFilePath, String apkResPath) throws IOException {
JarFile jarFile = new JarFile(apkFilePath);
JarEntry jarEntry = jarFile.getJarEntry(apkResPath);
return jarFile.getInputStream(jarEntry);
}
// Example usage reading the file "SecureManifest.xml" under "assets" folder:
File sdcard = Environment.getExternalStorageDirectory();
File apkFile = new File(sdcard, "file.apk");
if (apkFile.exists()) {
try {
InputStream is =getInputStreamFromApkResource(apkFile.toString(), "assets/SecureManifest.xml");
BufferedReader br = new BufferedReader( new InputStreamReader(is));
String str;
while ((str = br.readLine()) != null) {
Log.d("***", str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
The github gist can be found here

Categories

Resources