Open a file audio in R.Raw - android

I have to open a file that in the /res/raw/ folder, but it seems that android, doesn't recognize the path.
Here is my code:
public static void openRec()
{
//this is the wav file that I have to analyze
File file = new File("/res/raw/chirp.wav");
try {
FileInputStream in = new FileInputStream(file);
chirp = new byte[(int) file.length()];
in.read(chirp);
Log.d("xxx", "" + chirp.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT:
I have another method openRec in which, the path is passed as argument:
public static void openRec(String path) {
File file = new File(path);
try {
FileInputStream in = new FileInputStream(file);
recording = new byte[(int) file.length()];
in.read(recording);
Log.d("xxx", "" + recording.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I would a method that do the same thing but with the ffile in /res/raw. How do I that?

Use in this manner
public static void openRec()
{
//this is the wav file that I have to analyze
try {
InputStream in = getResources().openRawResource(R.raw.chirp);
chirp = new byte[(int) file.length()];
in.read(chirp);
Log.d("xxx", "" + chirp.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

file not playing from Internal storage in Android

here is string to setDataSource
/data/data/com.player/app_player/file.mp3
getting E/Exception: setDataSource failed.
here is the code:
mediaPlayer.setDataSource(context, Uri.parse("/data/data/com.player/app_player/file.mp3"));
I stored that file using this code
getContext().getDir("player", Context.MODE_PRIVATE)
which is same as /data/data/com.player/app_player
using content://data/data/com.player/app_player/file.mp3 did not work.
This is how I solve it.
String musicUrl = "";
if (songSavedInDB()) {
musicUrl = "here is any file path(Internal or external)"
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(musicUrl);
mPlayer.setDataSource(fileInputStream.getFD());
fileInputStream.close();
mPlayer.prepare();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
musicUrl = "here is url";
try {
mPlayer.setDataSource(getContext(), Uri.parse(musicUrl));
mPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}

Can't create file in the internal storage

i am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.

Storing a file to internal storage and reading it

What I am trying to do is store a JSON file as a string in internal storage to access it later. The reasoning behind this is to not have to access the server on every request, as this data is constant. Once it is stored once, it doesn't have to be retrieved again unless there is some sort of update. File storage isn't something I've done before, and I was hoping someone could give me a hand. My current code is throwing a null pointer exception at this line:
File file = new File(getFilesDir(), fileName);
My code:
protected String doInBackground(String[] runeId) {
String url = "https://prod.api.pvp.net/api/lol/static-data/" + region + "/v1.2/rune/" + runeId[0] + "?api_key=" + api_key;
JSONParser jsonParser = new JSONParser();
JSONObject runeInfo = jsonParser.getJSONFromUrl(url);
String jsonString = runeInfo.toString();
String fileName = "runeInfo";
File file = new File(getFilesDir(), fileName);
String readJson = null;
if(!runesCached) {
Log.d("Cache", "Caching File");
try {
FileOutputStream os = new FileOutputStream(file);
os.write(jsonString.getBytes());
os.close();
Log.d("Cache", "Cache Complete");
runesCached = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String name = null;
try {
FileInputStream fis;
File storedRuneInfo = new File(getFilesDir(), fileName);
fis = new FileInputStream(storedRuneInfo);
fis.read(readJson.getBytes());
JSONObject storedJson = new JSONObject(readJson);
try {
name = storedJson.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
}
Try this, instead:
File file = new File(getFilesDir().toString(), fileName);
getFilesDir() returns a File, not a String, which the File class constructor takes as a parameter.
getFilesDir()toString() should return something like /data/data/com.your.app/
EDIT:
This gives the same error. How about:
try {
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter(getFilesDir() + "/" + "filename");
out = new BufferedWriter(fstream);
out.write(jsonString.getBytes());
out.close();
} catch (Exception e){}

Write file to sdcard in android

I want to create a file on sdcard. Here I can create file and read/write it to the application, but what I want here is, the file should be saved on specific folder of sdcard. How can I do that using FileOutputStream?
// create file
public void createfile(String name)
{
try
{
new FileOutputStream(filename, true).close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// write to file
public void appendToFile(String dataAppend, String nameOfFile) throws IOException
{
fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
fosAppend.write(dataAppend.getBytes());
fosAppend.write(System.getProperty("line.separator").getBytes());
fosAppend.flush();
fosAppend.close();
}
Here's an example from my code:
try {
String filename = "abc.txt";
File myFile = new File(Environment
.getExternalStorageDirectory(), filename);
if (!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = string.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
And don't forget the:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Try like this,
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
try {
File file = new File(newFolder, "MyTest" + ".txt");
file.createNewFile();
} catch (Exception ex) {
System.out.println("ex: " + ex);
}
} catch (Exception e) {
System.out.println("e: " + e);
}
It's pretty easy to create folder and write file on sd card in android
Code snippet
String ext_storage_state = Environment.getExternalStorageState();
File mediaStorage = new File(Environment.getExternalStorageDirectory()
+ "/Folder name");
if (ext_storage_state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
if (!mediaStorage.exists()) {
mediaStorage.mkdirs();
}
//write file writing code..
try {
FileOutputStream fos=new FileOutputStream(file name);
try {
fos.write(filename.toByteArray());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
//Toast message sd card not found..
}
Note: 'getExternalStorageDirectory()'
actually gives you a path to /storage/emulated/0 and not the actual sdcard
'String path = Syst.envr("SECONDARY_STORAGE");' gives you a path to the sd card

Android:Cannot open file Not enough disk space

I have an application consist on reading AND saving an xml file and to write it if internet connection is available,else it will read the file already saved on the terminal.
WriteFeed function:
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
WriteFeed function:
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
I have enough diskSpace ,sometimes i get "MemoryCach will use up to 16 Mb" ,always i get "Not enough disk space,will not index" and "FeatureCode > cannot open file"
whats wrong in my app?

Categories

Resources