IllegalArgumentException: File contains a path separator Android - java

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) {
e.printStackTrace();
}
I would appreciate if someone can help identify the problem.

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);
to
outputStream = new FileOutputStream (new File(patternDirectory.getAbsolutePath().toString()), true); // true will be same as Context.MODE_APPEND

One problem may be the fact that you do:
Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/com.example.pattern1/myfile.txt"
You create a directory that has name myfile.txt

Related

Failing to write bytes in file

I have created a file and I want to write in bytes in this file but it's not working. Where is the problem?
public void writeFileExternalStorage() {
File file = new File(getExternalFilesDir(null), "hhh.txt");
try {
if(!file.exists())
file.createNewFile();
FileOutputStream outputStream ;
outputStream = new FileOutputStream(file, true);
outputStream.write(files.getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The createNewFile call will return true if it has successfully created the file. You should check the result of the call, and log an error if it is false.
According to the documentation for getExternalFilesDir (javadoc):
[it m]ay return null if shared storage is not currently available.
If that happens you will call new File(null, "hhh.txt"). That is equivalent to new File("hhh.txt") (javadoc), so the file would be created in the app's "current user directory".

How to find a path write to a json file in Android studio emulation?

I am trying use Android Studio emulation to produce a json in my apps. Is there a way to locate the directory and set it as path and implement it in the following?
......
DIRECTORY directory = createDummySchool();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File(filepath? + "sample.json"), directory);
}catch (IOException e) {
e.printStackTrace();}
.....
well it depends where you want to write your file in, Internal or external memory.
you can always write information in internal memory which can be accessible by your app but to write on external memory you will require permission like
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
To save file internally you can use this
getFilesDir();
String filename = "myfile";
File file = new File(context.getFilesDir(), filename);
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
refer this for more information, this is the best way and should be the first place where you should be looking, :)

Where is the saved file is stored ? in Android

I used this code, but I can't find the saved file anywhere !
String filename = "fichier";
String string = "bonjour";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
You will be able to find it if you open a new fileInputStream with the same parameters as your outputStream. You might also want to consider using SharedPreferences for something as simple as storing one String.

Writing a File in Android

First of all, I'm sorry if exists a similar post but I was not able to understand.
I'm trying to write a file in android and I got the following code:
String FILENAME = "hello_file.txt";
String string = "hello world!";
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Angles", "FileNotFoundException");
}catch(IOException e){
e.printStackTrace();
Log.d("Angles", "IOException");
}
I don't get any exception so I suppose it works but I'm not able to find the hello_file.txt file inside the device.
I'm running on Galaxy Nexus; no sd.
If you want to create a file in sdcard, you need to use
File f = new File (Environment.getExternalStorageDirectory(),"myfile.txt")

Writing a file to sdcard

I'm trying to write a file from an Http post reply to a file on the sdcard. Everything works fine until the byte array of data is retrieved.
I've tried setting WRITE_EXTERNAL_STORAGE permission in the manifest
and tried many different combinations of tutorials I found on the net.
All I could find was using the openFileOutput("",MODE_WORLD_READABLE) method, of the activity but how my app writes file is by using a thread. Specifically, a thread is invoked from another thread when a file has to be written,
so giving an activity object didn't work even though I tried it.
The app has come a long way and I cannot change how the app is currently written.
Please, someone help me?
CODE:
File file = new File(bgdmanip.savLocation);
FileOutputStream filecon = null;
filecon = new FileOutputStream(file);
byte[] myByte;
myByte = Base64Coder.decode(seReply);
bos.write(myByte);
filecon.write(myByte);
myvals = x * 11024;
bgdmanip.savLocation holds the whole files path. seReply is a string reply from HttpPost response. The second set of code is looped with reference to x. The file is created but remains 0 bytes.
//------------------------------WRITING DATA TO THE FILE ---------------------------------
btnWriteSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(v.getContext(),"Done writing SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show();
txtData.setText("");
}
catch (Exception e)
{
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
//---------------------------READING DATA FROM THE FILE PLACED IN SDCARD-------------------//
btnReadSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null)
{
aBuffer += aDataRow ;
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(v.getContext(),"Done reading SD 'mysdfile.txt'",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
ALONG WITH THIS ALSO WRITE THIS PERMISSION IN Android.Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The openFileOutput() method writes data to your application's private data area (not the SD card), so that's probably not what you want. You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
Here is a sample:
// Log used as debug
File log = new File(Environment.getExternalStorageDirectory(), "Log.txt");
try {
out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
out.write(new Date().toString());
out.write(" : \n");
} catch (Exception e) {
Log.e(TAG, "Error opening Log.", e);
}

Categories