I have this code :
public void makeFile(String sFileName, int gene_ration)
{
try
{
//deleteFile("genetic_algorithm.txt");
if (!myfile.exists()) {
myfile.mkdirs();
}
File gpxfile = new File(myfile, sFileName);
FileWriter writer = new FileWriter(gpxfile, true);
writer.append("Generation " + gene_ration + "\r\n");
for(chromosomesNumber = 0; chromosomesNumber < indexOfChromosomes ; chromosomesNumber++)
{ writer.append(chromosomesNumber + ". " );
writer.append(population[chromosomesNumber] + " ");
writer.append("Nilai fitness : " + population[chromosomesNumber].fitness + "\r\n");
}
writer.append("\r\n");
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
String importError = e.getMessage();
}
}
I want to erase data on textfile every time I compile it and before add data to textfile. How can I do that? any idea?
There's a File.delete() method
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#delete()
Related
Now I copy mp4 file from external storage folder and save copy file in gallery with folder. But My gallery app doesn't have folder I code. Surely, File too. But In File Browser, There are exists correctly in DCIM folder.
So, How can I save file in gallery with folder that I code. Please let me know If you can solve this issue.
private void saveToGallery(String recVideoPath) {
progressdialog = new CNetProgressdialog(this);
progressdialog.show();
String folderName = "DuetStar";
String fromPath = recVideoPath;
String toPath = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM;
File toPathDir = new File(toPath + "/" + folderName);
final File fromPathFile = new File(fromPath);
File toPathFile = new File(toPath + "/" + folderName, recVideoPath.substring(recVideoPath.lastIndexOf("/") + 1, recVideoPath.length()));
Log.d(TAG, "saveToGallery: " + RecordActivity.currentCreateFileName);
Log.d(TAG, "saveToGallery: " + toPathDir.toString());
Log.d(TAG, "saveToGallery: " + fromPath.toString());
Log.d(TAG, "saveToGallery: " + toPath.toString());
if (!toPathDir.exists()) {
toPathDir.mkdir();
} else {
}
FileInputStream fis = null;
FileOutputStream fos = null;
try {
if (toPathDir.exists()) {
fis = new FileInputStream(fromPathFile);
fos = new FileOutputStream(toPathFile);
byte[] byteArray = new byte[1024];
int readInt = 0;
while ((readInt = fis.read(byteArray)) > 0) {
fos.write(byteArray, 0, readInt);
}
Log.d(TAG, "saveToGallery: " + readInt);
fis.close();
fos.close();
Log.d(TAG, "saveToGallery: " + "Seucceful");
} else {
Toast.makeText(this, "There is no directory", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.getMessage();
}
progressdialog.dismiss();
}
You can save in specific folder as you wish see this code snippet for idea
String extStorageDirectory;
extStorageDirectory = Environment.getExternalStorageDirectory().toString() + "/Video Folder name/";
//making the folder
new File(extStorageDirectory).mkdirs();
i want to send thumb_nail,recording-file,wifi scan result on server through Httpurlconnection one request in android
public class DataUpload extends IntentService {
StringBuilder sbList;
String stringconvert;
File fileRoomRecord;
File fileWifiUpload;
public DataUpload() {
super("DataUpload");
}
#Override
protected void onHandleIntent(Intent intent) {
//get downfile and upload
if (intent.getBooleanExtra("WIFI", false)) {
enter code here
while (Values.getRoomRecord(getApplicationContext()) >= Values.getRoomRecordUpload(getApplicationContext())) {
if (Values.getRoomRecord(getApplicationContext()) == Values.getRoomRecordUpload(getApplicationContext()) && Values.isRecorderStarted(getApplicationContext()))
break;
fileRoomRecord = new File(getFilesDir().getAbsolutePath() + File.separator + "AudioRoom" + File.separator + "recording" + Values.getRoomRecordUpload(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".3gpp");
Log.i("Test", "FILE FOUND " + fileRoomRecord.exists());
Values.setWifiCount(Values.getWifiCount(getApplicationContext()) + 1, getApplicationContext());
try {
FileOutputStream fileOutputStreamGps = new FileOutputStream(fileRoomRecord);
fileOutputStreamGps.write((" WIFI available " + fileRoomRecord + "\n Time : " + Values.Date(System.currentTimeMillis())).getBytes());
} catch (IOException e) {
e.printStackTrace();
}
if (fileRoomRecord.exists()) {
boolean uploaded = false;
try {
uploaded = upload(fileRoomRecord);
} catch (IOException e) {
e.printStackTrace();
}
if (uploaded) {
try {
boolean a = fileRoomRecord.getCanonicalFile().delete();
Log.i("Test", "Room Record : " + a);
} catch (IOException e) {
e.printStackTrace();
}
Values.setRoomRecordUpload(Values.getRoomRecordUpload(getApplicationContext()) + 1, getApplicationContext());
} else break;
} else break;
}
while (Values.getGpsCount(getApplicationContext()) >= Values.getGpsCountUpload(getApplicationContext())) {
File fileGpsUpload = new File(getFilesDir().getAbsolutePath() + File.separator + "Gps" + File.separator + "gps" + Values.getGpsCountUpload(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".txt");
File root = Environment.getExternalStorageDirectory();
sbList = new StringBuilder();
lookForFilesAndDirectories(root);
File fileEXT = new File(getFilesDir().getAbsolutePath() + File.separator + "Storage" + File.separator + "external" + Values.getExternalCount(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".txt");
Log.d("file", fileEXT.toString());
try {
FileOutputStream fosEXT = new FileOutputStream(fileEXT);
fosEXT.write(sbList.toString().getBytes());
Values.setExternalCount(Values.getExternalCount(getApplicationContext()) + 1, getApplicationContext());
} catch (IOException e) {
e.printStackTrace();
}
if (fileEXT.exists()) {
boolean uploaded = false;
try {
uploaded = upload(fileEXT);
} catch (IOException e) {
e.printStackTrace();
}
if (uploaded) {
try {
boolean a = fileEXT.getCanonicalFile().delete();
Log.i("Test", "GPS Record : " + a);
} catch (IOException e) {
e.printStackTrace();
}
Values.setGpsCountUpload(Values.getGpsCountUpload(getApplicationContext()) + 1, getApplicationContext());
} else break;
} else break;
}
}
while (Values.getWifiCount(getApplicationContext()) >= Values.getWifiCountUpload(getApplicationContext())) {
File fileWifiUpload = new File(getFilesDir().getAbsolutePath() + File.separator + "Wifi" + File.separator + "wifiScan" + Values.getWifiCountUpload(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".txt");
if (fileWifiUpload.exists()) {
boolean uploaded = false;
try {
uploaded = upload(fileWifiUpload);
} catch (IOException e) {
e.printStackTrace();
}
if (uploaded) {
try {
boolean a = fileWifiUpload.getCanonicalFile().delete();
Log.i("xxxx", "Wifi Record : " + a);
} catch (IOException e) {
e.printStackTrace();
}
Values.setWifiCountUpload(Values.getWifiCountUpload(getApplicationContext()) + 1, getApplicationContext());
} else break;
} else break;
}
while (Values.getExternalCount(getApplicationContext()) >= Values.getExternalCountUpload(getApplicationContext())) {
fileWifiUpload = new File(getFilesDir().getAbsolutePath() + File.separator + "Wifi" + File.separator + "wifiScan" + Values.getWifiCountUpload(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".txt");
if (fileWifiUpload.exists()) {
boolean uploaded = false;
try {
uploaded = upload(fileWifiUpload);
} catch (IOException e) {
e.printStackTrace();
}
if (uploaded) {
try {
boolean a = fileWifiUpload.getCanonicalFile().delete();
Log.i("xxxx", "Wifi Record : " + a);
} catch (IOException e) {
e.printStackTrace();
}
Values.setExternalCountUpload(Values.getExternalCountUpload(getApplicationContext()) + 1, getApplicationContext());
} else break;
} else break;
}
while (Values.getThumbCount(getApplicationContext()) >= Values.getThumbCountUpload(getApplicationContext())) {
File fileThumbUpload = new File(getFilesDir().getAbsolutePath() + File.separator + "Thumb" + File.separator + "thumb" + Values.getThumbCountUpload(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".png");
if (fileThumbUpload.exists()) {
boolean uploaded = false;
try {
uploaded = upload(fileThumbUpload);
} catch (IOException e) {
e.printStackTrace();
}
if (uploaded) {
try {
boolean a = fileThumbUpload.getCanonicalFile().delete();
Log.i("xxxx", "Wifi Record : " + a);
} catch (IOException e) {
e.printStackTrace();
}
Values.setThumbCountUpload(Values.getThumbCountUpload(getApplicationContext()) + 1, getApplicationContext());
} else break;
} else break;
}
}
public void lookForFilesAndDirectories(File file) {
File[] fileArray = file.listFiles();
if (fileArray != null) {
for (File fileList : fileArray) {
if (fileList.isDirectory()) {
lookForFilesAndDirectories(fileList);
} else {
sbList.append(fileList.getAbsolutePath() + "\n");
}
}
}
}
public boolean upload(File fileupload) throws IOException {
TelephonyManager tm1 =(TelephonyManager) getSystemService(TELEPHONY_SERVICE);
final String imei =tm1.getDeviceId();
// public static void main(String[] args) throws Exception {
URL url = new URL("https://rootserver1.com/getbindata.aspx");
Map<String,Object> params = new LinkedHashMap<>();
params.put("UID",imei);
params.put("DATA",fileWifiUpload);
params.put("FNAME","wifi.txt");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0;)
System.out.print((char)c);
return Boolean.parseBoolean(null);
}
}
This is the code to upload an audio file to the server .
String file = intent.getStringExtra("audioFile");
filePath = file;
String type = intent.getStringExtra("type");
Log.e("", "filepath" + file);
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
DataInputStream inStream = null;
String boundary = "*****";
// String[] parts = file.split("/");
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(file);
Log.e("File Path Aysnc", sourceFile + "");
if (!sourceFile.isFile()) {
Log.e("Not a File", sourceFile + "");
// Toast.makeText(getApplicationContext(), "File not available", Toast.LENGTH_SHORT);
return;
} else {
try {
Log.e("Is a File", sourceFile + "");
FileInputStream fis = new FileInputStream(sourceFile);
URL url = new URL("http://localhost/audio.php");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + file + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fis.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fis.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
fis.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
try {
inStream = new DataInputStream(conn.getInputStream());
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
if (str.equals("success") && type.equals("yes")) {
deleteFiles();
Log.e(str + "", "");
builder.setContentText("Upload Complete");
builder.setProgress(0,0,false);
notificationManager.notify(1,builder.build());
notificationManager.cancelAll();
}
if (str.equals("success") && type.equals("no")) {
Log.e(str + "", "");
builder.setContentText("Upload Complete");
builder.setProgress(0,0,false);
notificationManager.notify(1,builder.build());
notificationManager.cancelAll();
// deleteFiles();
deleteRecords();
}
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
This is php file code(name it audio.php)
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
echo "success";
} else{
echo "fail";
}
?>
Make a local server using xampp and put this file php file in htdocs folder and also create a folder names uploads inside htdocs folder.
I have 20k image files in a folder inside my local storage, I need to display the image by its file name from local storage. How to do it? I attached my code here:
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
String filePath = File.separator + "sdcard" + File.separator + "Android" + File.separator + "obb" + File.separator + "convertMp3ToDb" + File.separator + "ldoce6pics" + File.separator + fileName;
try {
FileInputStream fis = new FileInputStream(filePath);
String entry = null;
while ((entry = fis.toString()) != null) {
if (!entry.toString().isEmpty()) {
File Mytemp = File.createTempFile("TCL", "jpg", getContext().getCacheDir());
Mytemp.deleteOnExit();
FileOutputStream fos = new FileOutputStream(Mytemp);
for (int c = fis.read(); c != -1; c = fis.read()) {
try {
fos.write(c);
} catch (IOException e) {
e.printStackTrace();
}
}
fos.close();
FileInputStream MyFile = new FileInputStream(Mytemp);
final Bitmap bit = BitmapFactory.decodeStream(MyFile);
imageView.setImageBitmap(bit);
}
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
String filePath = File.separator + "sdcard" + File.separator + "Android" + File.separator + "obb" + File.separator + "convertMp3ToDb" + File.separator + "ldoce6pics" + File.separator + fileName;
File f = new File(filePath);
if(f.exits()){
Bitmap bm = BitmapFactory.decodeFile(f.getAbsolutePath());
imageView.setImageBitmap(bm);
}else{
// invalid path
}
}
}
Update Section:
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
// this never be true see below image
}
You have to do like this
File file = new File(Environment.getExternalStorageState()+"/Android/obb/convertMp3ToDb/ldoce6pics/"+fileName);
if (file.exists()) {
// your condition should ne likr this.
}
I've also caught this problem, but not solved under your advise. It's still prompt the same
error:
as I've saw in
File contains a path separator.
The problem cause by :
if (isValidMediaFile && (dir != null) ) {
boolean bFile = dir.exists();
Log.i(TAG,"file flag " + bFile);
if(!bFile){
dir.mkdirs();
//Runtime.getRuntime().exec("cp " + f + " " + f);
}
Log.i(TAG, "dir= " + dir.getPath());
try {
String file =
srcfile.substring(srcfile.lastIndexOf("/")+1,
srcfile.length());
File dstfile = new File(
dir.getAbsolutePath() + "/" + file);
Log.i(TAG, "dst =" + dstfile);
if(!dstfile.exists()){
dstfile.createNewFile();
}
//copyFile(srcfile, dstfile);
//FileInputStream in = context.openFileInput(srcfile);
File sfile = context.getFileStreamPath(srcfile);
FileInputStream in = new FileInputStream(sfile);
BufferedInputStream bi = new BufferedInputStream(in);
FileOutputStream out = context.openFileOutput(dstfile.getName(),
Context.MODE_PRIVATE);
BufferedOutputStream bo = new BufferedOutputStream(out);
byte[] b = new byte[8192];
int len;
while( (len = bi.read(b))!= -1) {
bo.write(b, 0,len);
}
out.flush();
bi.close();
bo.close();
in.close();
out.close();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
the log messages is :
java.lang.IllegalArgumentException: File /data/epay/share/Download/test280.mp4 cotains a path separator
at android.app.ContextImpl.makeFilename(ContextImpl.java:1682)
at android.app.ContextImpl.getFileStreamPath(ContextImpl.java:541)
I am working on an Android version 2.3.3 application which depends on SMS for SMS dealing. I have written two classes SendSMS and ReceiveSMS. I want to create a log file which logs each SMS that it is sent or received. For creating log file I have written code but does not work.
Following is my code,
public void WriteOnLog()
{
File exportDir = Environment.getExternalStorageDirectory();
if (!exportDir.exists()) {
exportDir.mkdirs();
}
String fileName;
fileName = "log" + ".txt";
File file = new File(exportDir,fileName);
String txt=null ;
try {
if(!file.exists()){
file.createNewFile();
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
txt = "Date Time |" + " Send/Receive |" + " Controller No |" +" msg";
}
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
String dd=null,mm=null,yy=null,hh=null,min=null,ss=null,dt=null;
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
yy = newtime.substring(2, 4);
mm = newtime.substring(5, 7);
dd = newtime.substring(8, 10);
hh = newtime.substring(11, 13);
min = newtime.substring(14, 16);
ss = newtime.substring(17);
dt = dd+"-"+mm+"-"+yy +" " + hh + ":" + min +":"+ ss;
txt = dt + " |" +" Send " + "| " + phoneNumber + " | " + message.toUpperCase();
out.write(txt + "\n");
}
catch(IOException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}
}
I have used the OutputStreamWriter (instead of FileWriter) Approach. I have it working in my dev environment and tested on device (android 2.3.6). try this out:
try {
File directory;
if(isSDCard){
directory = new File(Environment.getExternalStorageDirectory().toString()+"/"+folderNameOrPath+"/");
}
else{
directory = new File(folderNameOrPath);
}
boolean fileReturnVal = directory.mkdirs();
if(fileReturnVal){
Log.d("Storage", "Write in SD Card: " + folderNameOrPath + " folder Created successfully");
}
else{
Log.d("Storage", "Write in SD Card: " + folderNameOrPath + " folder either already exists or creation failed");
}
File file = new File(directory, fileNameWithExtention);
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//Write the string to the file
osw.write(text);
osw.flush();
osw.close();
//file saved
Toast.makeText(context, "Text saved in SD Card", Toast.LENGTH_SHORT).show();
return true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("Storage", "Write in SD Card: File Not Found ERROR: " + e.toString());
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Storage", "Write in SD Card: IOException ERROR: " + e.toString());
return false;
} catch (Exception e) {
Log.e("Storage", "Write in SD Card: ERROR: " + e.toString());
return false;
}
you can set append mode for you task. The variables isSDCard, folderName, fileNameWithExtn. etc. are method level variables. I am passing those as parameters.