Write and Read a specific line from a text file on android - android

I want to read specific line from file like text.txt then write some string to it. any method to do that on android? I'm still play around with LineNumberReader, but still cant find way to do that.
Thanks.

Why not use a combination of inputstream, bufferedreader, stringbuilder, and an outputstream?

Maybe anybody get the same case like that..
private void Writing() {
// TODO Auto-generated method stub
try {
String[] lines = new String[888];
File internalStorage = Environment.getDataDirectory();
File dir = new File (internalStorage + "/myPde");
File file = new File(dir, "ekfslam.pde");
File file_temp = new File(dir, "ekfslam_temp.txt");
FileWriter fw = new FileWriter(file_temp,true);
BufferedWriter bw = new BufferedWriter(fw);
LineNumberReader lnr = new LineNumberReader(new FileReader(file));
file_temp.createNewFile();
int i = 0;
String Line = "";
while (true) {
Line = lnr.readLine();
if (Line != null) {
lines[i]=Line;
i++;
} else {
break;
}
}
for (int j = 0; j < 50; j+=5) {
lines[95] = lines[95]+"\n\t\t Data "+j;
}
if (file_temp.exists()) {
} else {
file_temp.createNewFile();
}
for (i = 0; i < lines.length; i++){
bw.write(lines[i]);
bw.newLine();
System.out.println(lines[i]);
}
file.delete();
file_temp.renameTo(file);
bw.close();
lnr.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Related

How to upload cordova filetransfer using server asp.net

i am creating an api that will recieve file from cordova file tranfer plugin.But while uploading , we are getting error "[10/19/2016 5:03:33 PM] azad singh: E/FileTransfer: {"target":"http://54.252.109.57:1031/api/Client/SaveDocument","http_status":500,"body":"\"Object reference not set to an instance of an object.\"","code":1,
[10/19/2016 5:03:45 PM] azad singh: Cordova - Camera"
[HttpPost]
[Route("Uploadfile")]
public string Uploadfile()
{
string msg = "";
try
{
HttpPostedFile file = HttpContext.Current.Request.Files["file"];
string saveFile = file.FileName;
//code to save the file
msg = "File uploaded";
}
catch (Exception ex)
{
msg = "Could not upload file: " + ex.Message;
}
return msg;
}
Please tell me where I am missing in my code...
This code works for me...
[HttpPost]
[Route("Uploadfile")]
public UploadFile Uploadfile()
{
HttpPostedFile file = HttpContext.Current.Request.Files["file"];
UploadFile uploadedfile = new UploadFile();
//HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Accepted);
try
{
if (file == null)
return uploadedfile ;
//response = Request.CreateResponse(HttpStatusCode.NotFound, "");
int count; int sum = 0;
byte[] buffer = new byte[file.ContentLength];
int length = (int)file.InputStream.Length;
buffer = new byte[length];
while ((count = file.InputStream.Read(buffer, sum, length - sum)) > 0)
sum += count;
FileVM fileObj = new FileVM();
NameValueCollection parameters = HttpContext.Current.Request.Params;
if (parameters.Keys.Count > 0)
{
fileObj.fileId = "";
fileObj.fileName = file.FileName.ToString();
fileObj.fileType = file.ContentType;
fileObj.filedata = "";
fileObj.LastDownLoad = parameters.GetValues("LastDownLoad")[0];
ServicecltClients srv = new ServicecltClients();
uploadedfile.FileId = srv.InsertDocumentAndRelatedClient(fileObj, buffer);
uploadedfile.FileType = fileObj.fileType;
//response = Request.CreateResponse<UploadFile>(HttpStatusCode.OK, uploadedfile);
}
}
catch (Exception _ex)
{
//response = Request.CreateResponse(HttpStatusCode.InternalServerError, _ex.Message);
ErrorLog.TraceErrorLog(_ex);
}
finally
{
file.InputStream.Close();
}
return uploadedfile;
}

How to Read from text file and Store into an Array in android

Hie Friends
I am developing an android application in that text file should be generated with some numbers. and after this one by one application should call to that numbers.
For eg:
9876452125,
9876452135,
9876452115,
Mostly that text file have 8 numbers which is Separated by "," and New Line "\n"
Now I want to read From that file line by line.
My Code for read file and store to array is:
public void read(String fname)
{
BufferedReader br = null;
try
{
StringBuffer output = new StringBuffer();
String fpath = "/sdcard/" + fname + ".txt";
br = new BufferedReader(new FileReader(fpath));
String line = null;
int index = 0;
String[][] num = new String[15][10];
List<String[]> collection = new ArrayList<String[]>();
while ((line = br.readLine()) != null)
{
if (index < num.length)
{
output.append(line);
// output.append("\n");
num[index] = line.split(",");
if (num.length > 0)
{
collection.add(num[index]);
}
}
Toast.makeText(getApplicationContext(), "" + collection, 5000)
.show();
index++;
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
Now My problem is when I printing collection to Toast it display some random strings. I don't know why??
Does any one have proper idea or sample code for how to read from file line by line and store to Array.
Thanks allot.
If I was you I'd use a scanner. You haven't given information on how you plan to store them: for example, why you use String[][] num = new String[15][10];, but I'll give you an example of if you wanted to store each number in it's own element, and you can adjust if necessary (I am assuming there is only one newline at the end of every line in your file).
public void read(String fname) {
String fpath = "/sdcard/" + fname + ".txt";
File file = new File(fpath);
Scanner scanner = new Scanner(new FileInputStream(file));
List<String[]> collection = new ArrayList<String[]>();
while (scanner.hasNextLine()){
String line = scanner.nextLine();
String.replaceAll("\n", ""); // strip the newline
String[] myList = myString.split(",");
for (i=0; i < myList.length; i++) {
collection.add(myList[i]);
}
}
scanner.close();
}
This doesn't have any android elements in it, but like I said you can adjust as necessary to do what you specifically need it to do.
ArrayList<ArrayList<String>> myArray = new ArrayList<ArrayList<String>>();
ArrayList<String> stringArray = new ArrayList<String>();
String random = "9876452125, 9876452135, 9876452115,";
String[] splitArray = random.split(",");
for (int i = 0; i < splitArray.length; i++) {
stringArray.add(splitArray[i]);
}
myArray.add(stringArray);
// printing all values
for (int i = 0; i < myArray.size(); i++) {
for (int j = 0; j < myArray.get(i).size(); j++) {
System.out.println("values of index " + i + " are :"
+ myArray.get(i).get(j));
}
}

How to save a multidimensional JSON array to a CSV file on Android?

I want to store large JSON array data into a CSV file. How can I do this?
I have following code which do not save any data into "test1.csv" file created in my android "test" folder.
Here is the code.
JSONArray outerArray = [{"value":true,"Id":0,"name":"214"}, {"value":true,"Id":0,"name":"215"},{"value":true,"Id":0,"name":"216"}]
public void saveCsv(JSONArray outerArray) throws IOException, JSONException {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/test/";
File dir = new File(rootPath);
if (!dir.exists()) {
dir.mkdir();
}
File file;
EditText editText = (EditText) findViewById(R.id.editText1);
if (!editText.getText().toString().equals("")) {
file = new File(rootPath, editText.getText().toString() + ".csv");
} else {
editText.setError("Defualt csv file name will be used");
Toast.makeText(this, "CSV name is empty", 5000).show();
file = new File(rootPath, "test1.csv");
}
file.createNewFile();
if (file.exists()) {
CSVWriter writer = new CSVWriter(new FileWriter(file), ',');
String[][] arrayOfArrays = new String[outerArray.length()][];
for (int i = 0; i < outerArray.length(); i++) {
JSONObject innerJsonArray = (JSONObject) outerArray.get(i);
String[] stringArray1 = new String[innerJsonArray.length()];
for (int j = 0; j < innerJsonArray.length(); j++) {
stringArray1[j] = (String) innerJsonArray.get("value");
}
arrayOfArrays[i] = stringArray1;
writer.writeNext(arrayOfArrays[i]);
}
writer.close();
}
}
I have used opencsv-2.3.jar from here http://sourceforge.net/projects/opencsv/. Documented here http://sourceforge.net/projects/opencsv/
I have following JSON with Boolean values which throws Boolean cant cast to string value
JSONArray outerArray = [{"value":true,"Id":0,"name":"214"}, {"value":true,"Id":0,"name":"215"},{"value":true,"Id":0,"name":"216"}]
i have changed json.get() to json.getString(). following code works fine now :)
public void saveCsv(JSONArray outerArray) throws IOException, JSONException {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/test/";
File dir = new File(rootPath);
if (!dir.exists()) {
dir.mkdir();
}
File file;
EditText editText = (EditText) findViewById(R.id.editText1);
if (!editText.getText().toString().equals("")) {
file = new File(rootPath, editText.getText().toString() + ".csv");
} else {
editText.setError("Defualt csv file name will be used");
Toast.makeText(this, "CSV name is empty", 5000).show();
file = new File(rootPath, "test1.csv");
}
if(!file.exists()){
file.createNewFile();
}
if (file.exists()) {
CSVWriter writer = new CSVWriter(new FileWriter(file), ',');
String[][] arrayOfArrays = new String[outerArray.length()][];
for (int i = 0; i < outerArray.length(); i++) {
JSONObject innerJsonArray = (JSONObject) outerArray.get(i);
String[] stringArray1 = new String[innerJsonArray.length()];
stringArray1[0]= (String) innerJsonArray.getString("Id");
stringArray1[1]= (String) innerJsonArray.getString("value");
stringArray1[2]= (String) innerJsonArray.getString("name");
arrayOfArrays[i] = stringArray1;
writer.writeNext(arrayOfArrays[i]);
}
writer.close();
}
}

What is the function of "Intent.ACTION_PRE_BOOT_COMPLETED"?

I want to know the exact functionality of Intent.ACTION_PRE_BOOT_COMPLETED. Currently, my requirement is to complete the task before the completion of booting of the device, i.e. before the call of Intent.ACTION_BOOT_COMPLETED.
Can anyone guide me on how to proceed to fulfill the requirement? Any help in this regard will be well appreciated.
ACTION_PRE_BOOT_COMPLETED is sended in ActivityManagerService.java::systemReady.
But to received it, the uid of your application must be system(1000).
for (int i=ris.size()-1; i>=0; i--) {
if ((ris.get(i).activityInfo.applicationInfo.flags
&ApplicationInfo.FLAG_SYSTEM) == 0) {
ris.remove(i);
}
}
Further more, this broadcast could only be received once in each upgrade( not very sure here, maybe should be each wipe data).
Note code below, if the target is in lastDoneReceivers, it will be removed.
ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
for (int i=0; i<ris.size(); i++) {
ActivityInfo ai = ris.get(i).activityInfo;
ComponentName comp = new ComponentName(ai.packageName, ai.name);
if (lastDoneReceivers.contains(comp)) {
ris.remove(i);
i--;
}
}
lastDoneReceivers is read from file /data/system/called_pre_boots.dat.
private static File getCalledPreBootReceiversFile() {
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
File fname = new File(systemDir, "called_pre_boots.dat");
return fname;
}
static final int LAST_DONE_VERSION = 10000;
private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
File file = getCalledPreBootReceiversFile();
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
int fvers = dis.readInt();
if (fvers == LAST_DONE_VERSION) {
String vers = dis.readUTF();
String codename = dis.readUTF();
String build = dis.readUTF();
if (android.os.Build.VERSION.RELEASE.equals(vers)
&& android.os.Build.VERSION.CODENAME.equals(codename)
&& android.os.Build.VERSION.INCREMENTAL.equals(build)) {
int num = dis.readInt();
while (num > 0) {
num--;
String pkg = dis.readUTF();
String cls = dis.readUTF();
lastDoneReceivers.add(new ComponentName(pkg, cls));
}
}
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
}
}
}
return lastDoneReceivers;
}
There is no such action as ACTION_PRE_BOOT_COMPLETED. I think that you normally can't fill your requirement. May be there is some mechanism for system signed apps to do that.

Cant read file in android

I am using this code in my project. I need to read .xls which i have placed in my raw folder.
ReadExcel test = new ReadExcel();
test.setInputFile(BitmapFactory.decodeStream(getClass().getResourceAsStream(("/SPPDashProject/res/raw/aging_busket_key.xls"))).toString());
try {
test.read();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
public class ReadExcel {
private String inputFile;
public void setInputFile(String inputFile) {
this.inputFile = inputFile;
}
public void read() throws IOException {
File inputWorkbook = new File(inputFile);
Workbook w;
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines
for (int j = 0; j < sheet.getColumns(); j++) {
for (int i = 0; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
CellType type = cell.getType();
if (cell.getType() == CellType.LABEL) {
System.out.println("I got a label: "
+ cell.getContents());
}
if (cell.getType() == CellType.NUMBER) {
System.out.println("I got a number "
+ cell.getContents());
}
}
}
} catch (BiffException e) {
e.printStackTrace();
}
}
}
what path should i give as my main read class takes path in string format.Plz suggest
You can use the following code:
Uri uri=Uri.parse("android.resource://com.mypackage.myapp" + R.raw.MyXLS);
String filePath=uri.getPath();
You should use the following code to open file in the /res/raw
getResources().openRawResource(R.raw.yourfilename)
You can put your file in the assets folder and use AssetManager to acess it.

Categories

Resources