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" />
Related
I have been trying to download a file in a target folder and rename it. This should be automatically done. Is this possible?
If yes, how should the code be written in Java?
Not too sure where you are trying to download from but as mentioned this my help: stackoverflow.com/a/921400/6743203
Alternatively refer to: https://www.mkyong.com/java/java-how-to-download-a-file-from-the-internet/
The renaming should look something like this, without a code example though it's hard to say what exactly you need:
import java.io.File;
public class FileRenameExample
{
public static void main(String[] args)
{
File oldFileName =new File("path/to/old_file_name.txt");
File newFileName =new File("path/to/new_file_name.txt");
if(oldFileName.renameTo(newFileName)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
}
File f = new File("YOUR-PATH/FileName.EXTENSION");
File fNew = new File("YOUR-PATH/NEW-FileName.EXTENSION");
if(f.renameTo(fNew)){
//do something
}
else{
//handle exception or throw custom exception
}
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
I have a cheerapp.mp3 in my /res/raw folder
so my code is
String filepath="/res/raw/cheerapp"; //or cheerapp.mp3
file = new File(filePath);
FileInputStream in = null;
try {
in = new FileInputStream( file );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The error I got file not found. why?
Use assets folder and ...
InputStream sound = getAssets().open("filename.mp3");
... or raw folder and ...
InputStream sound = getResources().openRawResource(R.raw.filename);
if it doesn't help you, then check this
Never can you access resource files by path!
Because they are compiled in APK file installed in Android. You can only access resource within application by access its generated resource id, from any activity (context):
InputStream cheerSound = this.getResources().openRawResource(R.raw.cheerapp);
or from view:
InputStream cheerSound = this.getContext().getResources().openRawResource(R.raw.cheerapp);
In your case, you should store sound files in external sd-card, then can access them by path. For e.g, you store your file in sounds folder on your sd-card:
FileInputStream inFile = new FileInputStream("/mnt/sdcard/sounds/cheerapp.mp3");
NOTE: path starts with '/' is absolute path, because '/' represents root in Unix-like OS (Unix, Linux, Android, ...)
Maybe you could use the AssetManager to manage your resources. For example:
AssetManager manager = this.getContext().getAssets();
InputStream open;
try {
open = manager.open(fileName);
BitmapFactory.Options options = new BitmapFactory.Options();
...
} catch (IOException e) {
e.printStackTrace();
}
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.
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