- Android – IllegalArgumentException: file contains path separator
- Best Solution
- Related Solutions
- Step 1:
- Step 2:
- Step 3:
- Step 4:
- Android – java.lang.IllegalArgumentException: contains a path separator
- Related Solutions
- Java – IllegalArgumentException: File contains a path separator Android
- Best Solution
- Related Solutions
Android – IllegalArgumentException: file contains path separator
I’m trying to check whether a zip exists in a subdirectory in the application’s internal storage:
File file = this.getApplicationContext().getFileStreamPath(this.getFilesDir().getAbsolutePath() + "/thesubdirectory/the.zip"; if(file.exists())
This is throwing a java.lang.IllegalArgumentException: File /data/data/my.package.name/files/thesubdirectory/the.zip contains a path separator .
Why is this happening? I thought this was the way you should check whether a file exists.
Best Solution
file.exists is. But getFileStreamPath can’t take a path, it needs to take a filename in that directory. Try this:
File file = new File(this.getFilesDir().getAbsolutePath() + "/thesubdirectory/the.zip");
Related Solutions
Android – way to get the source code from an APK file
Simple way: use online tool https://www.decompiler.com/, upload apk and get source code.
Procedure for decoding .apk files, step-by-step method:
Step 1:
- Make a new folder and copy over the .apk file that you want to decode.
- Now rename the extension of this .apk file to .zip (e.g. rename from filename.apk to filename.zip) and save it. Now you can access the classes.dex files, etc. At this stage you are able to see drawables but not xml and java files, so continue.
Step 2:
- Now extract this .zip file in the same folder (or NEW FOLDER).
- Download dex2jar and extract it to the same folder (or NEW FOLDER).
- Move the classes.dex file into the dex2jar folder.
- Now open command prompt and change directory to that folder (or NEW FOLDER). Then write d2j-dex2jar classes.dex (for mac terminal or ubuntu write ./d2j-dex2jar.sh classes.dex ) and press enter. You now have the classes.dex.dex2jar file in the same folder.
- Download java decompiler, double click on jd-gui, click on open file, and open classes.dex.dex2jar file from that folder: now you get class files.
- Save all of these class files (In jd-gui, click File -> Save All Sources) by src name. At this stage you get the java source but the .xml files are still unreadable, so continue.
Step 3:
Now open another new folder
- Put in the .apk file which you want to decode
- Download the latest version of apktool AND apktool install window (both can be downloaded from the same link) and place them in the same folder
- Open a command window
- Now run command like apktool if framework-res.apk (if you don’t have it get it here)and next
- apktool d myApp.apk (where myApp.apk denotes the filename that you want to decode)
now you get a file folder in that folder and can easily read the apk’s xml files.
Step 4:
It’s not any step, just copy contents of both folders(in this case, both new folders) to the single one
and enjoy the source code.
Android – What file system path is used by Android’s Context.openFileOutput()
Re the openFileOutput() method on the Context class to open a file for writing, what internal storage file path does it write to?
It points to where getFilesDir() on Context returns. You can tell this because the documentation says:
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
Related Question
Android – java.lang.IllegalArgumentException: contains a path separator
The openFileInput method doesn’t accept path separators.
Related Solutions
Android – Strange OutOfMemory issue while loading an image to a Bitmap object
To fix the OutOfMemory error, you should do something like this:
BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 8; Bitmap preview_bitmap = BitmapFactory.decodeStream(is, null, options);
This inSampleSize option reduces memory consumption.
Here’s a complete method. First it reads image size without decoding the content itself. Then it finds the best inSampleSize value, it should be a power of 2, and finally the image is decoded.
// Decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f) < try < // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, o); // The new size we want to scale to final int REQUIRED_SIZE=70; // Find the correct scale value. It should be the power of 2. int scale = 1; while(o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE) < scale *= 2; >// Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); > catch (FileNotFoundException e) <> return null; >
Android – Fling gesture detection on grid layout
Thanks to Code Shogun, whose code I adapted to my situation.
Let your activity implement OnClickListener as usual:
public class SelectFilterActivity extends Activity implements OnClickListener < private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private GestureDetector gestureDetector; View.OnTouchListener gestureListener; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); /* . */ // Gesture detection gestureDetector = new GestureDetector(this, new MyGestureDetector()); gestureListener = new View.OnTouchListener() < public boolean onTouch(View v, MotionEvent event) < return gestureDetector.onTouchEvent(event); >>; > class MyGestureDetector extends SimpleOnGestureListener < @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) < try < if (Math.abs(e1.getY() - e2.getY()) >SWIPE_MAX_OFF_PATH) return false; // right to left swipe if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) < Toast.makeText(SelectFilterActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show(); >else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) < Toast.makeText(SelectFilterActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show(); >> catch (Exception e) < // nothing >return false; > @Override public boolean onDown(MotionEvent e) < return true; >> >
Attach your gesture listener to all the views you add to the main layout;
// Do this for each view added to the grid imageView.setOnClickListener(SelectFilterActivity.this); imageView.setOnTouchListener(gestureListener);
Watch in awe as your overridden methods are hit, both the onClick(View v) of the activity and the onFling of the gesture listener.
public void onClick(View v)
The post ‘fling’ dance is optional but encouraged.
Java – IllegalArgumentException: File contains a path separator Android
I’m trying to write to an output file on my HTC One and get the following message in the LogCat:
11-21 08:05:18.228: W/System.err(6609): java.lang.IllegalArgumentException: File /storage/emulated/0/com.example.pattern1/myfile.txt contains a path separator
The source code is given below:
protected void writeToFile(String string) < File patternDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/com.example.pattern1/myfile.txt"); patternDirectory.mkdirs(); FileOutputStream outputStream; try < outputStream = openFileOutput(patternDirectory.getAbsolutePath().toString(), Context.MODE_APPEND); outputStream.write(string.getBytes()); TextView t = (TextView)findViewById(R.id.bottomMidText); t.setText(patternDirectory.getAbsolutePath().toString()); outputStream.close(); >catch (Exception e)
I would appreciate if someone can help identify the problem.
Best Solution
The openFileInput method will not accept path separators.(‘/’)
it accepts only the name of the file which you want to open/access. so change the statement
outputStream = openFileOutput(patternDirectory.getAbsolutePath().toString(), Context.MODE_APPEND);
outputStream = new FileOutputStream (new File(patternDirectory.getAbsolutePath().toString()), true); // true will be same as Context.MODE_APPEND
Related Solutions
Python – How to check whether a file exists without exceptions
If the reason you’re checking is so you can do something like if file_exists: open_it() , it’s safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.
If you’re not planning to open the file immediately, you can use os.path.isfile
Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.
import os.path os.path.isfile(fname)
if you need to be sure it’s a file.
Starting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7):
from pathlib import Path my_file = Path("/path/to/file") if my_file.is_file(): # file exists
if my_file.is_dir(): # directory exists
To check whether a Path object exists independently of whether is it a file or directory, use exists() :
if my_file.exists(): # path exists
You can also use resolve(strict=True) in a try block:
try: my_abs_path = my_file.resolve(strict=True) except FileNotFoundError: # doesn't exist else: # exists
Python – How to copy a file in Python
shutil has many methods you can use. One of which is:
from shutil import copyfile copyfile(src, dst) # 2nd option copy(src, dst) # dst can be a folder; use copy2() to preserve timestamp
- Copy the contents of the file named src to a file named dst . Both src and dst need to be the entire filename of the files, including path.
- The destination location must be writable; otherwise, an IOError exception will be raised.
- If dst already exists, it will be replaced.
- Special files such as character or block devices and pipes cannot be copied with this function.
- With copy , src and dst are path names given as str s.
Another shutil method to look at is shutil.copy2() . It’s similar but preserves more metadata (e.g. time stamps).
If you use os.path operations, use copy rather than copyfile . copyfile will only accept strings.