I am trying to make a program which can join 2 MP3 files and save them on the android SD card. I have Java code that is working but when I try to convert it to Android it gives some error.
In Java code is written below. It's working perfect.
import java.io.*;
public class TuneDoorJava {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fistream1 = new FileInputStream("F:\\aa.mp3"); // first source file
FileInputStream fistream2 = new FileInputStream("F:\\bb.mp3");//second source file
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
FileOutputStream fostream = new FileOutputStream("F:\\final.mp3");//destinationfile
int temp;
while( ( temp = sistream.read() ) != -1)
{
// System.out.print( (char) temp ); // to print at DOS prompt
fostream.write(temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}
In Android, what I'm trying to do is:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// FileOutputStream fostream=null;
FileInputStream fist=(FileInputStream)getResources().openRawResource(R.raw.t);
FileInputStream fist2=(FileInputStream)getResources().openRawResource(R.raw.v);
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1");
dir.mkdirs();
File file = new File(dir, "filename");
//FileInputStream fistream1 = new FileInputStream(); // first source file
//FileInputStream fistream2 = new FileInputStream("F:\\bb.mp3");//second source file
SequenceInputStream sistream = new SequenceInputStream(fist, fist2);
FileOutputStream fostream = new FileOutputStream(file);
int temp;
while( ( temp = sistream.read() ) != -1)
{
// System.out.print( (char) temp ); // to print at DOS prompt
fostream.write(temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}
- Give this permission WRITE_EXTERNAL_STORAGE
Here is the working code from my project:
public class ConcateSongActivity extends Activity {
Button mbutt;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mbutt = (Button)findViewById(R.id.button_Click_Karo);
mbutt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
FileInputStream fis1 = new FileInputStream("/sdcard/viv0.wav");
FileInputStream fis2 = new FileInputStream("/sdcard/viv1.wav");
SequenceInputStream sis = new SequenceInputStream(fis1,fis2);
FileOutputStream fos = new FileOutputStream(new File("/sdcard/vis.wav"));
int temp;
try {
while ((temp = sis.read())!= -1){
fos.write(temp);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
You need to give your app the permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Related
Now I have app which save and read some text into .txt file by button. How can I make that app save file after app closed and reading file when app opened automatically, without any click on buttons?
public class mAcitivity extends AppCompatActivity {
private Button btn_read, btn_save;
private TextView textView;
private String txt = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveFile();
}
});
btn_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
readFile();
textView.setText(txt);
}
});
}
public String readFile() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/TEST");
myDir.mkdirs();
File file = new File(myDir, "file.txt");
try {
FileInputStream fis = new FileInputStream(file);
int size = fis.available();
byte[] buffer = new byte[size];
fis.read(buffer);
fis.close();
txt = new String(buffer);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mActivity.this, "Error reading file", Toast.LENGTH_LONG).show();
}
return txt;
}
public void saveFile() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/TEST");
myDir.mkdirs();
File file = new File(myDir, "file.txt");
if (file.exists()){ file.delete();}
try {
String sometxt = "Hello world";
FileOutputStream out = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(out);
pw.println(sometxt);
pw.flush();
pw.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can use your MainActivity lifecycle callbacks to begin your I/O operations directly, or start BoundService which will operate them.
You can achieve this by putting your saveFile() method inside stop() lifecycle method, and putting your readFile() method inside start() lifecycle method. Activity will automatically call start() method once the application starts and it will call stop() method once the applicqtion closes/terminates.
I want to add a feature to my app in which the users can upload files (PDF files) from their mobile to the database, then download this file back to the app and display it.
I have no idea how to start doing this and what is the right code to use.
I tried using this code,
ParseObject pObject = new ParseObject("ExampleObject");
pObject.put("myNumber", number);
pObject.put("myString", name);
pObject.saveInBackground(); // asynchronous, no callback
- EDIT -
I tried this code but the app crashes when I click the button:
public class Test extends Activity {
Button btn;
File PDFFile;
ParseObject po;
String userPDFFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
po = new ParseObject("pdfFilesUser");
btn = (Button) findViewById(R.id.button);
PDFFile = new File("res/raw/test.pdf");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadPDFToParse(PDFFile, po, userPDFFile);
}
});
}
private ParseObject uploadPDFToParse(File PDFFile, ParseObject po, String columnName){
if(PDFFile != null){
Log.d("EB", "PDFFile is not NULL: " + PDFFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(PDFFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] pdfBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(PDFFile.getName() , pdfBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
}
You can upload a file manually via REST API. Take a look at this docs here
Can try this code:
private ParseObject uploadPDFToParse(File PDFFile, ParseObject po, String columnName){
if(PDFFile != null){
Log.d("EB", "PDFFile is not NULL: " + PDFFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(PDFFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] pdfBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(PDFFile.getName() , pdfBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
For more details check this
I would strongly suggest you quickly get up to speed with the Parse Java development wiki.
To answer your question. You want to be using:
byte[] data = "Working at Parse is great!".getBytes();
ParseFile file = new ParseFile("resume.txt", data);
file.saveInBackground();
First declare your file etc then save it using that. But once again, first read the guidelines to better understand the framework you working with.
https://parseplatform.github.io/docs/android/guide/
I want to write a project that on first run or installation it copies files and folders from Assets folder( app_webview,cache,databases,files,lib,shared_prefs ) which are folders inside Assets Folder to /data/data/com.example.app/ I saw a code like this around here
i solved this by using this code. you can use this code to send any file from Assets/files/ to any where you want by replacing the getFilesDir().getParent() with the values i will provide below but i havent figure out how to send Folders
package com.paresh.copyfileassetstoAssets;
public class CopyFileAssetsToSDCardActivity1 extends Activity {
/** Called when the activity is first created. */
Button button1;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
CopyAssets();
}
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("Files");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("Files/"+filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream(getFilesDir().getParent().toString() + "/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
intent = new Intent(CopyFileAssetsToSDCardActivity1.this, CopyFileAssetsToSDCardActivity2.class);
startActivity(intent);
}
});
}
}
I'm not able to understand these classes. I've been trying to create a new file in a new directory on my internal storage, put some text in it and then to read it out. This does not seem to work without the ContextWrapper. So I tried this:
public class DownloadActivity extends Activity {
...
class Download extends AsyncTask<String, Void, String>{
....
private void searchAndSave(String s) throws IOException {
....
ContextWrapper cw = new ContextWrapper(getBaseContext());
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
File fileInFolder = new File(folder, "fileInFolder");
String string = "Hello world!";
FileOutputStream outputStream = openFileOutput("fileInFolder",
Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
File fl = new File(cw.getDir("folder", Context.MODE_PRIVATE)+"/fileInFolder");
FileInputStream fin = new FileInputStream(fl);
BufferedReader reader = new BufferedReader(
new InputStreamReader(fin));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
String result = sb.toString();
reader.close();
fin.close();
}
}
Creating the file does not work without the ContextWrapper. I've been reading a lot, but I still have problems to understand, what the Context and the Contextwrapper actually do and why I need them to create a file. Additionally in my code the creating of the FileInputStream does not work. When the program reaches
FileInputStream fin = new FileInputStream(fl);
I always get the error:
05-21 11:18:25.721: W/System.err(7344): java.io.FileNotFoundException:
/data/data/com.example.dice/app_folder/fileInFolder: open failed:
ENOENT (No such file or directory)
I really would appreciate some help with understanding and solving this problem.
UPDATE: I made a more spare Activity, maybe now it's easier to reconstruct the whole thing. (Should I have done this in a new answer, or is it okay to edit my first posting?) Even though I don't get an error message when trying to create a file, is doesn't seem to work. Here I try reading the "Hello world" string, but I get a FileNotFoundException (EISDIR). Just for you to know :)
public class FolderActivity extends Activity {
public final static String TAG = "FolderActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_folder);
Button button = (Button) findViewById(R.id.button_folder);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
folder();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void folder() throws IOException{
Log.d(TAG, "folder");
ContextWrapper cw = new ContextWrapper(getBaseContext());
Log.d(TAG, "cw = new ContextWrapper");
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
Log.d(TAG, "folder = cw.getDir");
File fileInFolder = new File(folder, "fileInFolder");
Log.d(TAG, "fileInFolder = new File");
/*Log.d(TAG,
"fileInFolder.getAbsolutePath()"
+ fileInFolder.getAbsolutePath());*/
String string = "Hello world!";
// Aksioms suggestion
if (!fileInFolder.exists() && !fileInFolder.mkdirs()) {
Log.e("file", "Couldn't create file " + fileInFolder);
} else { Log.d(TAG, "file created"); }
FileOutputStream outputStream = openFileOutput("fileInFolder",
Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
Log.d(TAG,
"fileInFolder.getAbsolutePath()"
+ fileInFolder.getAbsolutePath());
String s = fileInFolder.getAbsolutePath();
try {
getStringFromFile(s);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
}
You are trying to open a file which does not exists.
Make sure that you check and create the file if it does not exsist:
if (!fl.exists() && !fl.mkdirs()) {
Log.e("file", "Couldn't create file " + fl);
}
EDIT:
Yes the getDir creats the folder if it is not created.
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
But the problem is here
File fileInFolder = new File(folder, "fileInFolder");
String string = "Hello world!";
FileOutputStream outputStream = openFileOutput("fileInFolder",
Context.MODE_PRIVATE);
In here you try to open a file that does not exsist, you just constructed a new file named fileInFolder, but you actually do not have that folder yet.
Try to use the code that I wrote at the first place, before the openFileOutput("fileInFolder", Context.MODE_PRIVATE); :
if (!fileInFolder.exists() && !fileInFolder.mkdirs()) {
Log.e("file", "Couldn't create file " + fileInFolder);
}
Try this and tell me how it goes.
EDIT 2:
OK I found the problem it was so obvious. The mistake was that we created the fileInFolder as a directory, and you can not write anything there :D
What we should have done is this:
Remove my code for creating the fileInFolder.
if (!fileInFolder .exists() && !fileInFolder .mkdirs()) {
Log.e("file", "Couldn't create file " + fileInFolder );
} else {
Log.d(TAG, "file created");
}
we do not need to create it because we will use it as a file. So the change I have made in your code is this:
FileOutputStream outputStream = new FileOutputStream(fileInFolder);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outputStream));
out.write(string);
out.close();
Add this between the line String string = "Hello world!"; and the first Log.d... This is the correct way to write in a file.
The whole code:
public class MainActivity extends Activity {
public final static String TAG = "FolderActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button_folder);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
folder();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void folder() throws IOException {
Log.d(TAG, "folder");
ContextWrapper cw = new ContextWrapper(getBaseContext());
Log.d(TAG, "cw = new ContextWrapper");
File folder = cw.getDir("folder", Context.MODE_PRIVATE);
Log.d(TAG, "folder = cw.getDir");
File fileInFolder = new File(folder, "fileInFolder");
Log.d(TAG, "fileInFolder = new File");
/*
* Log.d(TAG, "fileInFolder.getAbsolutePath()" +
* fileInFolder.getAbsolutePath());
*/
String string = "Hello world!";
FileOutputStream outputStream = new FileOutputStream(fileInFolder);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outputStream));
out.write(string);
out.close();
Log.d(TAG,
"fileInFolder.getAbsolutePath()"
+ fileInFolder.getAbsolutePath());
String s = fileInFolder.getAbsolutePath();
try {
getStringFromFile(s);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getStringFromFile(String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
// Make sure you close all streams.
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}}
Check if you have this permission in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I hope everything is clear now.
public class MainActivity extends Activity {
FileInputStream fistream2,fistream1;
File newFile=new File(Environment.getExternalStorageDirectory()
+File.separator
+"newfolder" //folder name
+File.separator
+"media"
+File.separator
+"player"+File.separator+"theonkar10.mp3");
File newFile1=new File(Environment.getExternalStorageDirectory()
+File.separator
+"newfolder" //folder name
+File.separator
+"media"
+File.separator
+"player"+File.separator+"1.mp3");
File newFile2=new File(Environment.getExternalStorageDirectory()
+File.separator
+"newfolder" //folder name
+File.separator
+"media"
+File.separator
+"player"+File.separator+"2.mp3");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
myMethod();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void myMethod() throws IOException
{
FileInputStream fistream1 = new FileInputStream(newFile1.getAbsolutePath()); // first source file
FileInputStream fistream2= new FileInputStream(newFile2.getAbsolutePath());//second source file
//SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
// FileOutputStream fostream = new FileOutputStream("C:\\Temp\\final.mp3");//destinationfile
FileOutputStream fostream=new FileOutputStream(newFile.getAbsolutePath(),true);
if(!newFile.exists()){
newFile.mkdirs();
int temp;
while( ( temp = sistream.read() ) != -1)
{
System.out.print( (char) temp ); // to print at DOS prompt
fostream.write(temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}
}
I am getting a new file theonkar10.mp3 but the file is of 0 bytes.Probably I am missing a simple step.
three things to get this thing working ^^
create the FILE not the directory!
newFile.createNewFile();
then another important part is: create the fileoutputstream AFTER you created the file!
and third, it seems the sequenceinputstream works not properly for me, when i use the two-arguemnt-constructor, instead use the constructor with the enumerator.
here's the summary ^^
public void myMethod() throws IOException
{
FileInputStream fistream1 = new FileInputStream(newFile1 ); // first source file
FileInputStream fistream2= new FileInputStream(newFile2 );//second source file
Vector<FileInputStream> v = new Vector<FileInputStream>();
v.add(fistream1);
v.add(fistream2);
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
if(!newFile.exists()){
newFile.createNewFile();
FileOutputStream fostream=new FileOutputStream(newFile, true);
int temp;
while( ( temp = sistream.read() ) != -1)
{
System.out.print( (char) temp ); // to print at DOS prompt
fostream.write((byte)temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}
it's working here with my env...