i have a video file in my external directory. how can i load it to inputstream variable.
For the time being i am reading file in the res/raw folder but i want to read it from the sdcard. also i dont know about the name of the file but its path will be recieved through intent.
check the following code
public class SonicTest extends Activity
{
VideoView videoView;
String uri;
InputStream soundFile;
File file;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void play(View view)
{
new Thread(new Runnable()
{
public void run()
{
float speed= (float) 1.0;
float pitch= (float) 1.5;
float rate= (float) 1.0;
uri= Environment.getExternalStorageDirectory().toString();
uri=uri+"/video.3gp";
AndroidAudioDevice device = new AndroidAudioDevice(22050, 1);
Sonic sonic = new Sonic(22050, 1);
byte samples[] = new byte[4096];
byte modifiedSamples[] = new byte[2048];
InputStream soundFile = null;
//soundFile = getContentResolver().openInputStream(Uri.parse(uri));
soundFile=getResources().openRawResource(R.raw.video3);
Log.i("testing","check if SoundFile is correct "+soundFile);
int bytesRead;
if(soundFile != null) {
sonic.setSpeed(speed);
sonic.setPitch(pitch);
sonic.setRate(rate);
do {
try {
bytesRead = soundFile.read(samples, 0, samples.length);
} catch (IOException e) {
e.printStackTrace();
return;
}
if(bytesRead > 0) {
sonic.putBytes(samples, bytesRead);
} else {
sonic.flush();
}
int available = sonic.availableBytes();
if(available > 0) {
if(modifiedSamples.length < available) {
modifiedSamples = new byte[available*2];
}
sonic.receiveBytes(modifiedSamples, available);
device.writeSamples(modifiedSamples, available);
}
} while(bytesRead > 0);
device.flush();
}
}
} ).start();
}}
Try
File file = new File(Uri.toString());
FileInputStream fileInputStream = new FileInputStream(file);
Then you can read from the stream.
String fileName = "OfflineMap/maps.xml";
String path = Environment.getExternalStorageDirectory()+"/"+fileName;
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
Here is a working code, you can InputStream with a storage file:
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"Demo.xml");
InputStream fileInputStream = new FileInputStream(file);
soundFile = openFileInput(uri);
Related
Does anyone use the CameraKit-Android by gogopop? My problem is that I set the listener of video but the outputfile is null. Anyone know how to solve it?
this is my code:
cameraView.getCamera().setVideoQuality(CameraKit.Constants.VIDEO_QUALITY_720P);
cameraView.getCamera().startRecordingVideo();
cameraView.getCamera().setCameraListener(new CameraListener() {
#Override
public void onVideoTaken(final File video) {
super.onVideoTaken(video);
/* new Thread(new Runnable() {
#Override
public void run() {
final byte[] videoBytes = FileUtils.File2byte(video.getAbsolutePath());
if (!isExit) {
new Thread(new Runnable() {
#Override
public void run() {
saveFile(videoBytes);
}
}).start();
}
isExit = false;
}
}).start();*/
}
});
I've used to make a new file to save the mp4, but when I'm recording a video longer than one minute, the app is OOM. Anyone can help me? Thanks.
i slove it. this is not cameraKit-android issuse. it is the Android 's problem,it have two point:
the file is exit, but you don't notification the system. so you should :
cameraView.getCamera().setCameraListener(new CameraListener() {
#Override
public void onVideoTaken(final File video) {
super.onVideoTaken(video);
//notify system refresh
Uri localUri = Uri.fromFile(video);
Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
sendBroadcast(localIntent);
try this guys idea, i use it save susscess:
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/milai/";
File appDir = new File(path);
if (!appDir.exists()) {
appDir.mkdir();
}
mVideoFile = new File(mPreview.getView().getContext().getExternalFilesDir(null), getPicTime()+".mp4");
String myFile = path+getPicTime()+".mp4";
mMediaRecorder.setOutputFile(myFile);
it look the same , but i don't know why success. if eveybody have other problem, can ask me . i will try to help you.
My solution for this problem;
public static void saveVideoToFile( File video) {
try {
File newfile;
FileInputStream fileInputStream = new FileInputStream(video);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/" + "Your File Name" + "/");
if (!dir.exists()) {
dir.mkdirs();
}
newfile = new File(dir, "save_" + System.currentTimeMillis() + ".mp4");
if (newfile.exists()) newfile.delete();
OutputStream out = new FileOutputStream(newfile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = fileInputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
fileInputStream.close();
out.close();
MyLog.log("Copy file successful.");
} catch (Exception e) {
e.printStackTrace();
}
}
I want to render a pdf which in the raw folder with ParcelFileDescriptor tried too many methods from the other posts but none of them worked for me. Below is the code
I copied the code from the post you suggested and modified my code but still pdf is not opening even its showing no error.
public void render()
{
try
{
imgv = (ImageView) findViewById(R.id.img);
int w = imgv.getWidth();
int h = imgv.getHeight();
Bitmap bm = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_4444);
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abcd.pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + "abcd.pdf");
// File file = new File("android.resource://com.nyt.ilm.mytestpdfreader/raw/abcd.pdf");
PdfRenderer render = new PdfRenderer(ParcelFileDescriptor.open(file,ParcelFileDescriptor.MODE_READ_ONLY));
if (CurrentPage < 0)
{ CurrentPage =0;
}
else if (CurrentPage > render.getPageCount()){
CurrentPage = render.getPageCount() - 1;
}
Matrix m = imgv.getImageMatrix();
Rect rect = new Rect(0,0,w,h);
render.openPage(CurrentPage).render(bm,rect,m,PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imgv.setImageMatrix(m);
imgv.setImageBitmap(bm);
imgv.invalidate();
}
catch (Exception e)
{
e.printStackTrace();
}
}
//method to write the PDFs file to sd card
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase("abcd.pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
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);
}
}
I want use sendFileMessage in sendbird api. It need file value and I want use this file from drawable (or assets). sendBird API
this is snipped code from sendbird
Hashtable<String, Object> info = Helper.getFileInfo(getActivity(), uri);
final String path = (String) info.get("path");
File file = new File(path);
String name = file.getName();
String mime = (String) info.get("mime");
int size = (Integer) info.get("size");
sendFileMessage(file, name, mime, size, "", new BaseChannel.SendFileMessageHandler() {
public void onSent(FileMessage fileMessage, SendBirdException e) {
if (e != null) {
return;
}
mAdapter.appendMessage(fileMessage);
mAdapter.notifyDataSetChanged();
}
});
This code working well which I got uri from open image intent. but I want to use to other purpose and I want to replace this code
File file = new File(path);
become something like
File file = new File(<path or uri from drawable or assets>);
I have tried with uri
Uri uri = Uri.parse("android.resource://com.package.name/raw/filenameWithoutExtension");
File file = new File(uri.getPath());
with inputStream
try {
File f=new File("file name");
InputStream inputStream = getResources().openRawResource(R.raw.myrawfile);
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (IOException e){}
always failed in getting file and return error code ERR_REQUEST_FAILED 800220
Have you tried like below?
String fileName = FILE_NAME;
File cachedFile = new File(this.getActivity().getCacheDir(), fileName);
try {
InputStream is = getResources().openRawResource(R.raw.sendbird_ic_launcher);
FileOutputStream fos = new FileOutputStream(cachedFile);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
fos.write(buf, 0, len);
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
groupChannel.sendFileMessage(cachedFile, fileName, "image/jpg", (int) cachedFile.length(), "", new BaseChannel.SendFileMessageHandler() {
#Override
public void onSent(FileMessage fileMessage, SendBirdException e) {
}
});
This works for me.
There is an image file inside a directory. How to copy this image file into another directory that was just created ? The two directories are on the same internal storage of the device :)
You can use these functions. The first one will copy whole directory with all children or a single file if you pass in a file. The second one is only usefull for files and is called for each file in the first one.
Also note you need to have permissions to do that
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Functions:
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
If you want to copy image programtically then use following code.
File sourceLocation= new File (sourcepath);
File targetLocation= new File (targetpath);
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
** Use FileUtils This Is Simple Fast And Best method and Download Jar file from here**
public void MoveFiles(String sourcepath) {
File source_f = new File(sourcepath);
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsappStatus/yourfilename.mp4";
File destination = new File(destinationPath);
try
{
FileUtils.copyFile(source_f , destination);
}
catch (IOException e)
{
e.printStackTrace();
}
}
Go To Link For FileUtils Jar
Here is code given below..wenever i try to open dat activity it shows the target file doesnt exist..please help me.....thanks in advance
public class MainActivityAlgb extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_algb);
CopyReadAssets();
}
private void CopyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "cure.pdf");
try
{
in = assetManager.open("cure.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + getFilesDir() + "/cure.pdf"), "application/pdf");
startActivity(intent);
}
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);
}
}
}
As per my understanding you have stored the file in res folder.I assume that it is inside raw folder, if not move it to raw folder.Then you can get the file input stream as
InputStream is = getResources().openRawResource(R.raw.yourFile);
Hope this helps.