hey I have a problem with loading data from a txt file
private void read() {
try {
// open the file for reading
InputStream instream = openFileInput(File.separator + "bla.txt");
// if file the available for reading
if (instream.available() >0) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = buffreader.readLine()) != null) {
for(int i= 0; i<=1; i++){
if(i == 0){
bla = Integer.parseInt(buffreader.readLine());
}
if(i == 1){
bla2 = Integer.parseInt(buffreader.readLine());
}
}
// close the file again
instream.close();
Toast.makeText(getBaseContext(),
"Ladevorgang war efolgreich!",
Toast.LENGTH_LONG).show();
}}
}
catch (java.io.FileNotFoundException e) {
Toast.makeText(getBaseContext(),
"Datei nicht vorhanden",
Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
Please help me I dont know what I should change:(
I alway got the android.content.res.Resources$NotFoundException: String resource ID #0x0
Thanks for help Strik3r
private void save() {
try {
File myFile = new File(Environment.getExternalStorageDirectory() + File.separator + "bla.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(string.toString() + "\n");
myOutWriter.append(string2.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Gespeichert",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
this is the save data
// open the file for reading
InputStream instream = openFileInput(File.separator + "bla.txt");
does not seem to be a valid file.
Instead, please try
InputStream instream = openFileInput(Environment.getExternalStorageDirectory() +File.separator + "bla.txt");
Related
I am trying to download an e-book from URL and unzip it, which further goes for display. While the same unzip logic works perfectly for a FTP download, when it comes to URL, unzipping method does nothing after download.
My book download calling method :
DownloadBook db = new DownloadBook(localFile,"some url",book.key,context,(TaskListener) result -> {
if (result) {
runOnUiThread(() -> pBar.setVisibility(View.VISIBLE));
Runnable t = (Runnable) () -> {
unzip(localFile.getPath(), b.key.replace(".zip",""), b);
isDownloaded = true;
//Deleting downlaoded zip file
System.out.println("zip file deleted - "+localFile.delete());
String urls = localFile.getPath() + "/" + ((b.key).replace(".zip", ""));
System.out.println("URL IS " + urls);
System.out.println("Going for Display");
GlobalVars.title = b.title;
Intent intent = new Intent(My_Library.this, DisplayActivity.class);
startActivity(intent);//
};
t.run();
} else {
runOnUiThread(() ->
{
alert = new AlertDialog.Builder(this);
alert.setTitle("Error");
alert.setMessage("Could not download. Please try again !")
.setCancelable(true)
.setNegativeButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(My_Library.this, My_Library.class);
startActivity(intent);
dialog.cancel();
}
});
alert.create();
alert.show();
}
);
}
});
The zip file download method :
t = new Thread(new Runnable() {
#Override
public void run() {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("some url");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(localFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
System.out.println("Total is "+total);
if(fileLength>0)
{
System.out.println("File length is "+fileLength+" local file length is "+localFile.length());
percent = (int) (total * 100 / fileLength);
System.out.println("FTP_DOWNLOAD bytesTransferred /downloaded -> " + percent);
mProgress.setProgress(percent);
}
output.write(count);
output.flush();
}
mListener.finished(true);
} catch (Exception e) {
e.printStackTrace();
mListener.finished(false);
} finally {
try {
output.flush();
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
The unzip method
public void unzip(String _zipFile, String _targetLocation, Book b) {
pBar.setVisibility(View.VISIBLE);
GlobalVars.path = _targetLocation;
_targetLocation = getApplicationContext().getFilesDir().getPath();
dirChecker(_targetLocation);
try {
BufferedInputStream fin = new BufferedInputStream(new FileInputStream(_zipFile));
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
System.out.println("Unzipping file -> " + ze.getName());
//create dir if required while unzipping
if (ze.isDirectory()) {
dirChecker(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
} else {
File f = new File(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
dirChecker(f.getParent());
long size = f.length();
BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(new File(String.valueOf(f.getAbsoluteFile()))));
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
fout.write(buffer, 0, read);
}
zin.closeEntry();
fout.close();
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}
The FTP download class method Unzip works absolutely fine. But as I try to put download from url, it just downloads but not unzips.
You have to change the output buffer writing method.
So instead of, in zip download method
output.write(count);
Use,
output.write(data,0,count);
I am trying to delete a specific line from a file, but when I run this, it returns me all the files, deleted. More specific i have a favorite button at a video fragment and i want when user press it ,to write the title of video in file (already done) and when unpress it to delete it....
my.java class is:
private void writeToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/config.txt");
FileOutputStream fos = new FileOutputStream(file,true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (!file.exists()) {outputStreamWriter.write(g);}
outputStreamWriter.append("\n"+g +"\n");
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private void deleteToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
outputStreamWriter.write(text.toString());
}
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.favorite:
if(showingFirst==true) {
Context context = getActivity();
CharSequence text = "Added to Favorites";
int duration = Toast.LENGTH_SHORT;
item.setIcon(R.drawable.heart_off);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
writeToFile(title,context);
showingFirst=false;
} else {
Context context = getActivity();
CharSequence text = "Deleted from Favorites";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
deleteToFile(title,context);
item.setIcon(R.drawable.heart_wh);
showingFirst=true;
}
break;
case R.id.home:
Intent k=new Intent(getActivity(),MainActivity.class);
Log.i(TAG, "onNavigationItemSelected: ");
startActivity(k);
break;
}
return false;
}
So, problem lies at below line of codes where you are trying to open file for Read and Write simultaneously
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
Instead, I would suggest you to read your file completely and then at the end you should write to the file (overwrite).
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
//start writing from here
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
outputStreamWriter.write(text.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
}
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
This line:
FileOutputStream fos = new FileOutputStream(file);
resets contents of the file (ie replaces it with empty file). I recommend you add logging and/or debug your code so you will have a better understanding of what is going on.
I have a file stored locally on my device that I read from perfectly fine if I don't reboot the phone. When I reboot and read the logs, new FileReader throws an NPE; why?
BufferedReader br = null;
FileReader fr = null;
try {
Log.d("DEBUG", "Before filereader");
fr = new FileReader(ABS_FILENAME);
Log.d("DEBUG", "Before BufferedReader");
br = new BufferedReader(fr);
String current;
Log.d("DEBUG", "About to read file");
while((current = br.readLine()) != null) {
}
}
} catch (Exception e) {
Log.d("DEBUG", "Exception thrown: " + e.getMessage());
} finally {
try {
if (fr != null) {
fr.close();
}
} catch (IOException ex) {
Log.d("DEBUG", "Problem closing file reader");
}
}
return null;
The above code happens in a broadcast receiver. ABS_FILENAME is a string that denotes a file. That file is written to periodically in an Activity once something is clicked:
// in an onClick that gets invoked
try {
String line = myKey + " " + myValue;
fw.write(line);
fw.write(System.getProperty("line.separator"));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// elsewhere in the activity
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
myFile = new File(getFilesDir(), FILENAME);
try {
if (!myFile.exists()) {
myFile.createNewFile();
}
ABS_FILENAME = myFile.getAbsolutePath();
fw = new FileWriter(myFile.getAbsoluteFile(), true);
} catch(IOException e) {
}
If
new FileReader(ABS_FILENAME)
really produces a NullPointerException, clearly ABS_FILENAME must be null.
I am using tesseract OCR in my app (Spl!t). When I launch the app from Eclipse to my phone, eng.traineddata is copied into /storage/emulated/0/Pictures/Receipts/tessdata/. But when I installed the app from the market, the eng.traineddata file is not copied into the folder. Is there something wrong with my code?
private File getOutputPhotoFile() {
directory = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Receipts");
dataPath = directory.getAbsolutePath();
if (!directory.exists()) {
directory.mkdirs();
Toast.makeText(Trans_List.this, "Receipts Folder Created", Toast.LENGTH_SHORT).show();
File tessDir = new File(directory, "tessdata");
if (!tessDir.exists()) {
tessDir.mkdirs();
Toast.makeText(Trans_List.this, "Tessdata Folder Created", Toast.LENGTH_SHORT).show();
File trainingData = new File(tessDir, "eng.traineddata");
if(!trainingData.exists())
new CopyLibrary().execute(LANG);
}
}
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
.format(new Date());
return new File(directory.getPath() + File.separator + "Receipt_"
+ timeStamp + ".jpg");
}
private class CopyLibrary extends AsyncTask<String, Void, Void> {
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);
}
#Override
protected Void doInBackground(String... s) {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("Spl!t", "Failed to get asset file list.");
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(dataPath + File.separator
+ "tessdata" + File.separator, LANG
+ ".traineddata");
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
Toast.makeText(Trans_List.this, "Tessdata copied", Toast.LENGTH_SHORT).show();
out = null;
} catch (IOException e) {
Log.e(TAG, "Failed to copy asset file");
}
}
return null;
}
}
I have created a txt file and saved it in the file Explorer at data/data/com.xxx/files/mynote/txt when I entered a string into edit text and click the button.
I want compare txt file content and input String. In my txt file, only minimum length 5 to 6 is stored. How do I do this? I have tried but it can not compare properly - it goes to else block part when I entered the same string as i save in my txt file like "tazin".
Here is my code.
btnSubmitCode=(Button)findViewById(R.id.button_Submit);
btnSubmitCode.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(editText_Code.getText().toString().isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Enter Code", Toast.LENGTH_SHORT).show();
}
else
{
String strCode = editText_Code.getText().toString().trim();
create_File(strCode);
readFile();
}
String temp;
String searchString = "tazin";
try {
File file=new File("/data/data/com.xxxxx/files/mynote.txt/");
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.readLine() != null)
{
temp = in.readLine();
System.out.println("String from txt file ="+temp);
if(searchString.equals(temp))
{
System.out.println("word is match");
in.close();
return;
}
else
{
System.out.println("word is not match");
}
}
in.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//Write File
private void create_File(String strtext)
{
FileOutputStream fos = null;
try
{
fos = openFileOutput("mynote.txt", MODE_PRIVATE);
fos.write(strtext.getBytes());
Toast.makeText(getApplicationContext(), "File created succesfully",
Toast.LENGTH_SHORT).show();
}
catch(FileNotFoundException fexception)
{
fexception.printStackTrace();
}
catch(IOException ioexception)
{
ioexception.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
// drain the stream
fos.flush();
fos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//Read File
private void readFile()
{
FileInputStream fis;
try
{
fis = openFileInput("mynote.txt");
byte[] reader = new byte[fis.available()];
while (fis.read(reader) != -1)
{
}
textView_ReadCode.setText(new String(reader));
strReadFile = new String(reader);
System.out.println("Read File Into String Format " + strReadFile);
Toast.makeText(getApplicationContext(), "File read succesfully",
Toast.LENGTH_SHORT).show();
if (fis != null)
{
fis.close();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
Log.e("Read File", e.getLocalizedMessage());
}
}
You're misusing the BufferedReader.readLine() method. You're calling it twice each time through your while loop; once in the while conditional, and once in the loop block itself. So, when you do temp = in.readLine() and then the searchString.equals(temp) comparison, you've already skipped a line from the text file. Structure your loop like so:
temp = in.readLine();
while (temp != null)
{
System.out.println("String from txt file =" + temp);
if(searchString.equals(temp))
{
System.out.println("word is match");
in.close();
return;
}
else
{
System.out.println("word is not match");
}
temp = in.readLine();
}
Edit:
Per our chat in comments, here is the updated code for what you need:
btnSubmitCode.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
String str = editText_Code.getText().toString();
if(str == null || str.equals(""))
{
Toast.makeText(getApplicationContext(), "Please Enter Code", Toast.LENGTH_SHORT).show();
}
else
{
String strCode = str.trim();
if(checkCode(strCode))
{
System.out.println("word is match");
}
else
{
System.out.println("word is not match");
}
}
}
}
);
...
...
// Returns true if the code has already been used
// Returns false if the code is new
// Creates mynote.txt if it doesn't exist
// Appends code if it is new
private boolean checkCode(String code)
{
String temp;
File file = new File(getFilesDir() + "mynote.txt");
if(file.exists())
{
try
{
BufferedReader in = new BufferedReader(new FileReader(file));
temp = in.readLine();
while (temp != null)
{
if(code.equals(temp))
{
// Match was found
// Clean up and return true
in.close();
return true;
}
temp = in.readLine();
}
in.close();
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
}
}
// Match was not found or File doesn't exist
// Append code to mynote.txt and return false
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
out.newLine();
out.write(code);
out.close();
}
catch (IOException e)
{
}
return false;
}
In your question you wrote different path then you write in your code so just check your path of file.