There is a problem with access to file via Windows Explorer. My files are saved on non root device. I can see them only using embedded file manager installe on Android Device, but there is problem with looking them with Windows Explorer. I plug-in and plug-out my device, but it doesn't work good. Here is my code:
public class LoggerUtil {
private File sdRoot;
private String dir;
private File workingDirectory;
private File log;
private Context applicationContext = MApp.getContext();
public LoggerUtil() {
}
#SuppressLint("SimpleDateFormat")
public File createNewLogFile() {
String currentDateandTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String path = sdRoot.toString() + dir + "log" + currentDateandTime + ".txt";
return new File(path);
}
#SuppressLint("SimpleDateFormat")
public void appendLog(String text) {
sdRoot = Environment.getExternalStorageDirectory();
dir = "/Android/data/" + applicationContext.getPackageName() + "/log/";
workingDirectory = new File(sdRoot, dir);
workingDirectory.mkdirs();
log = createNewLogFile();
if (ABC.isOK()) {
File logFile = log;
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
// BufferedWriter for performance, true to set append to file
// flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(currentDateandTime + " " + text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My execution is:
LoggerUtil loger = new LoggerUtil();
loger.appendLog("TEST");
Related
I Created a Image at the location. And I can see The Image got created
String Dirlocation = "Pictures/MyDirectoryName";
String mImageName = System.currentTimeMillis()+".jpg";
createFile(mDirectoryPath,mImageName,fileData);
private String createFile(String mDirectoryPath, String mImageName, byte[] fileData) throws IOException {
FileOutputStream out=null;
try{
File root = Environment.getExternalStoragePublicDirectory(mDirectoryPath);
File dir = new File(root + File.separator);
if (!dir.exists()) dir.mkdir();
//Create file..
String mFinalUri = root + File.separator + mImageName;
File file = new File(mFinalUri);
file.createNewFile();
out = new FileOutputStream(file);
if(out!=null){
out.write(fileData);
MediaScannerConnection.scanFile(context, new String[] { file.getPath() }, new String[] { "image/jpg" }, null);
}
//Check if file exists if true return the URI
File mFile = new File(mFinalUri);
if(mFile.exists()){
return mFinalUri;
}else{
return null;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally {
out.close();
}
return mDirectoryPath;
}
How to delete all the images in that directory ?
I tried with:
String mDirectoryPath = "Pictures/MyDirectoryName";
File dir = new File(mDirectoryPath);
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
Images inside the directory is not getting deleted
dir.isDirectory() is failing and saying its not a directory
How to Delete images properly ?
In your delete code you should be using
File dir = Environment.getExternalStoragePublicDirectory(mDirectoryPath)
And not
File dir = new File(mDirectoryPath);.
In your code the file will point to "/Pictures/MyDirectoryName"; which doesn't exist (your app doesn't have permission to write on the root /)
Trying to create folder in internal storage but code working only in oppo handset not in other brand handsets like samsung,mi etc
public void createPDF()
{
TextView dttt = (TextView)findViewById(R.id.dttt);
String da = dttt.getText().toString();
final Cursor cursor = db.getDateWise(da);
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CollactionApp"+ "/PDF";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
int i = 1;
File file = new File(dir, "Datewise" + da + ".pdf" );
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
}
// Check premissions in Manifest and at run time
String root_sd = Environment.getExternalStorageDirectory().toString();
createExDirectory("CollactionApp", root_sd);
String path = root_sd + "/CollactionApp"+ "/PDF.pdf";
File f = new File(path);
try {
if (!f.exists()) {
f.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
public static String createExDirectory(String folderName, String pathToExternalStorage) {
String returnPath = "";
boolean success = false;
Boolean isSDPresent = Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED);
if (isSDPresent) {
// SD-card is present
File appDirectory = new File(pathToExternalStorage + "/" + folderName);
if (appDirectory.exists()) {
success = true;
} else {
success = appDirectory.mkdirs();
}
if (success) {
returnPath = appDirectory.getAbsolutePath();
} else {
}
}
return returnPath;
}
The path you are using points to the external storage. I've had an app before which have been working for long on all devices until recently, so I had to do a refactor on it, so I don't use the getExternalStorageDirectory() anymore.
I now use the Context's getFilesDir(), on which I didn't get the same issue again.
You would want your path to be something like below to use internal storage.
File internalDir = getContext().getFilesDir();
File myFolder = new File(internalDir, "/CollactionApp"+ "/PDF");
String path = myFolder.getAbsolutePath;
Can you let me know , whether the below command is the correct
one for video audio merge ?
vabsolutePath= video file absolute path (only video),
aabsolutePath= audio file absolute path (only audio)
String ccommand[] = {"-i",vabsolutePath,"-i",aabsolutePath, "-c:v", "copy", "-c:a", "aac","-shortest", dabsolutePath};
The below code is used in android for merging.
Here the issue is the code is executing, but the output merge file "result.mp4" is not playable/not produced.
Could you please help to find out the issue in code/ command?
public class Mrge extends AppCompatActivity {
private Button var_button_save,var_button_send;
Uri vuri=null;
public String vabsolutePath=null, aabsolutePath=null, dabsolutePath=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message_layout);
OutputStream out;
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
InputStream ins = getResources().openRawResource(
getResources().getIdentifier("anvkl",
"raw", getPackageName()));
byte[] buf = new byte[1024];
int n;
while (-1 != (n = ins.read(buf)))
stream.write(buf, 0, n);
byte[] bytes = stream.toByteArray();
String root = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
File createDir = new File(root + "master" + File.separator);
createDir.mkdir();
File file = new File(root + "master" + File.separator + "master.mp4");
file.createNewFile();
out = new FileOutputStream(file);
out.write(bytes);
out.close();
vabsolutePath = file.getAbsolutePath();
//-------------------------------------------------------------------
ins = getResources().openRawResource(
getResources().getIdentifier("audio",
"raw", getPackageName()));
while (-1 != (n = ins.read(buf)))
stream.write(buf, 0, n);
bytes = stream.toByteArray();
root = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
createDir = new File(root + "audio" + File.separator);
createDir.mkdir();
file = new File(root + "audio" + File.separator + "audio.aac");
file.createNewFile();
out = new FileOutputStream(file);
out.write(bytes);
out.close();
aabsolutePath = file.getAbsolutePath();
root = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
createDir = new File(root + "result" + File.separator);
createDir.mkdir();
file = new File(root + "result" + File.separator + "result.mp4");
file.createNewFile();
dabsolutePath = file.getAbsolutePath();
//------------------------------------------------------------------------
} catch (IOException e) {
e.printStackTrace();
}
String ccommand[] = {"-y", "-i",vabsolutePath,"-i",aabsolutePath, "-c:v", "copy", "-c:a", "aac","-shortest", dabsolutePath};
loadFFMpegBinary();
execFFmpegBinary(ccommand);
}
FFmpeg ffmpeg;
private void loadFFMpegBinary() {
try {
if (ffmpeg == null) {
ffmpeg = FFmpeg.getInstance(this);
}
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
#Override
public void onFailure() {
//showUnsupportedExceptionDialog();
}
#Override
public void onSuccess() {
}
});
} catch (FFmpegNotSupportedException e) {
//showUnsupportedExceptionDialog();
} catch (Exception e) {
}
}
private void execFFmpegBinary(final String[] command) {
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler()
{
#Override
public void onFailure(String s) {
}
#Override
public void onSuccess(String s) {
}
#Override
public void onProgress(String s) {
}
#Override
public void onStart() {
}
#Override
public void onFinish() {
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
String m="hi";
}
}
}
While it is not possible to give you a concrete answer due to lacking details I will say yes, assuming:
Your ffmpeg command is implemented properly in your code and provides no errors.
You are outputting to an appropriate output format container for your video and audio formats.
The vabsolutePath contains only video and aabsolutePath contains only audio. Otherwise use the -map option to manually select streams instead of relying on the default stream selection behavior. Otherwise it may select the wrong streams.
Try creating destination(output) file in the below way-
File moviesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES
);
boolean success = true;
if (!moviesDir.exists()) {
success = moviesDir.mkdir();
}
if(success) {
File dest = new File(moviesDir, filePrefix + fileExtn);
int fileNo = 0;
while (dest.exists()) {
fileNo++;
dest = new File(moviesDir, filePrefix + fileNo + fileExtn);
}
....//execute ffmpeg command with dest.getAbsolutePath() as an output file path
}else
{
Snackbar.make(mainlayout, "Unable to create directory", 4000).show();
}
Use dest.getAbsolutePath() as an output file path to ffmpeg command.You can change desired directory as per your requirement.
I am trying to write a text file for logging in my app. When it comes to execution, there are READ-ONLY EXCEPTION and hence cannot write the text file.
only file 1" can be executed
Now using 5.0.1
The below is my code :
public static void writefile(String text )
{
File externalStorageDir = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download" );
String fileName= date() + ".txt" ;
File dir = new File(externalStorageDir , File.separator + "eyedebug" );
boolean statement = dir.exists() && dir.isDirectory();
if(!statement) {
// do something here
dir.mkdirs();
System.out.println("file 1");
}
File myFile = new File(dir.getAbsolutePath() , File.separator + fileName );
if(!myFile.exists()){
try {
myFile.createNewFile();
System.out.println("file 2");
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
FileWriter fileWritter = new FileWriter(myFile.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.append(text);
bufferWritter.newLine();
System.out.println("file 3");
bufferWritter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
after long work finally i found your solution, just implement below code it will help you..
public static void writefile(String text )
{
File externalStorageDir = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/eyedebug/" );
String fileName= System.currentTimeMillis() + ".txt" ;
boolean statement = externalStorageDir.exists() && externalStorageDir.isDirectory();
if(!statement) {
// do something here
externalStorageDir.mkdirs();
System.out.println("file 1");
}
File myFile = new File(externalStorageDir.getAbsolutePath() , fileName );
if(!myFile.exists()){
try {
myFile.createNewFile();
System.out.println("file 2");
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
FileWriter fileWritter = new FileWriter(myFile,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.append(text);
bufferWritter.newLine();
System.out.println("file 3");
bufferWritter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
add write permission WRITE_EXTERNAL_STORAGE in your manifest file.
Add following lines in your manifest file
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
There are two ways to print application log into a file.
If you want to get all loged events then you can use following method that used command line to save logs into file.
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -f "+ filename + " -v time -d *:V";
Log.d("FB Error Log", "command: " + command);
try{
Runtime.getRuntime().exec(command);
}
catch(IOException e){
e.printStackTrace();
}
}
else you can use following method to save indivisual logs into file.
public static void appendLog(String text) {
File logFile = new File("sdcard/app_log.txt");
try {
if (!logFile.exists()) {
logFile.createNewFile();
}
//BufferedWriter for performance, true to set append to file flag
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String format = "[dd/MM/yy HH:mm:ss]";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
String currentTime = sdf.format(date);
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(currentTime+" - "+text);
buf.newLine();
buf.close();
}
catch (Exception e) {
Log.e("StaticUtils", e.getMessage(), e);
}
}
Dont forget to add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
My question simply is that how do I save string HTML as .html file in internal storage. Please let me know how to do this.
Lets say string I have is:
string html="<html><head><title>Title</title></head><body>This is random text.</body></html>"
Tryout This.
private void saveHtmlFile() {
String path = Environment.getExternalStorageDirectory().getPath();
String fileName = DateFormat.format("dd_MM_yyyy_hh_mm_ss", System.currentTimeMillis()).toString();
fileName = fileName + ".html";
File file = new File(path, fileName);
String html = "<html><head><title>Title</title></head><body>This is random text.</body></html>";
try {
FileOutputStream out = new FileOutputStream(file);
byte[] data = html.getBytes();
out.write(data);
out.close();
Log.e(TAG, "File Save : " + file.getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
You can convert with this
public static String saveHtml(Activity activity, String html) {
String filePath = "";
String fileName = "";
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&&
activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]
{Manifest.permission.WRITE_EXTERNAL_STORAGE}, ARE_Toolbar.REQ_VIDEO);
return "";
}
filePath = Environment.getExternalStorageDirectory() +
File.separator + "ARE" + File.separator;
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdir();
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-
dd_hh_mm_ss");
String time = dateFormat.format(new Date());
fileName = time.concat(".html");
File file = new File(filePath + fileName);
if (!file.exists()) {
boolean isCreated = file.createNewFile();
if (!isCreated) {
com.chinalwb.are.Util.toast(activity, "Cannot create file
at: " + filePath);
return "";
}
}
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(html);
fileWriter.close();
com.chinalwb.are.Util.toast(activity, fileName + " has been saved
at " + filePath);
} catch (IOException e) {
e.printStackTrace();
com.chinalwb.are.Util.toast(activity, "Run into error: " +
e.getMessage());
}
return filePath + fileName;
}
**Call this method as -**
saveHtml(this, html);
Try This:
public void writeHTML() throws IOException
{
String html="<html><head><title>Title</title></head><body>This is random text.</body></html>"
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("myfile.html", Context.MODE_PRIVATE));
outputStreamWriter.write(html);
outputStreamWriter.close();
}
If it helps somebodey, there is a simple solution.
Youse saveWebarchive.
In Kotlin:
webView.loadUrl(URL);
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
return false
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
webView.saveWebArchive("$filesDir/myPage.mht")
}
}
And you can simple load it
webView.loadUrl("$filesDir/myPage.mht");