I'm trying to read some text from a .txt file, here's my code:
String filePath = bundle.getString("filepath");
StringBuilder st = new StringBuilder();
try {
File sd = Environment.getExternalStorageDirectory();
File f = new File(sd, filePath);
FileInputStream fileis = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(
fileis));
String line = new String();
while ((line = buf.readLine()) != null) {
st.append(line);
st.append('\n');
}
Log.i("egor", "reading finished, line is " + line);
} catch (FileNotFoundException e) {
Log.i("egor", "file not found");
} catch (IOException e) {
Log.i("egor", "io exception");
}
reader.setText(st.toString());
The text looks like this:
This is a sample text to test
The .txt file is created in Windows notepad.
And here's what I'm getting:
What's wrong with my code? Thanks in advance.
Is the file in utf-8 (unicode) format? For some reason, Notepad always adds a byte-order mark to unicode files, even when the byte-order is irrelevant. When interpreted as ASCII or ANSI, the BOM will be seen as several characters. It's possible this is what's causing your problem.
If so, the solution is to use a more competent text editor than Notepad, or write code that checks for a BOM first in all unicode files.
If none of this makes sense to you, try googling 'unicode' and 'byte-order mark'.
Wrap a FileReader object in the BufferedReader object instead.
http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileReader.html
File sd = Environment.getExternalStorageDirectory();
File file = new File(sd, filePath);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
st.append(line);
st.append("\n");
}
br.close();
Try with the folowing code
File f = new File(str);
FileInputStream fis = new FileInputStream(f);
byte[] mydata1 = new byte[(int) f.length()];
fis.read(mydata1);
System.out.println("...data present in 11file..."+new String(mydata1));
Related
I am trying to create an android app in which it will take the contents of the file which is in assets, copy the contents to the file in filestorage. Then while displaying, it will read the file in filestorage and will append the lines in edittext.
The problem i am facing is empty lines are not being read.
Following is the code snippet in which i am reading the contents of asset file and copying it in file "current.txt" which will be stored in filestorage.
reader = new BufferedReader(new InputStreamReader(getAssets().open("pravachan.txt")));
ContextWrapper contextWrapper=new ContextWrapper(getApplicationContext());
File directory= contextWrapper.getDir("FileStorage",Context.MODE_PRIVATE);
File myInternalFile=new File(directory,"current.txt");
FileWriter filewriter = new FileWriter(myInternalFile);
BufferedWriter out = new BufferedWriter(filewriter);
String mLine = reader.readLine();
while (mLine != null)
{
//process line
if(mLine.isEmpty())
{
out.write(" ");
String str = System.getProperty("line.separator");
out.write(str);
}
else
out.write(mLine);
mLine = reader.readLine();
}
out.close();
Following is the code snippet in which i am appending the edittext with contents of "current.txt" file
ContextWrapper contextWrapper=new ContextWrapper(getApplicationContext());
File directory= contextWrapper.getDir("FileStorage", Context.MODE_PRIVATE);
File myInternalFile=new File(directory,"current.txt");
FileInputStream fis=new FileInputStream(myInternalFile);
BufferedReader reader=new BufferedReader(new InputStreamReader(fis));
String mLine = reader.readLine();
TextView tv = (TextView)findViewById(R.id.editText);
while(mLine != null)
{
if(mLine.isEmpty()) {
tv.append(" ");
String str = System.getProperty("line.separator");
tv.append(str);
}
else
tv.append(mLine);
mLine = reader.readLine();
}
I don't want empty lines to be skipped.I want the file as it is to be displayed in Edittext. Please Help. Thanks in advance!
I got the answer!
Instead of doing out.write(str) in which str is the line separator, I did out.newline(). It worked!
I am writing data in file continuously in append mode using FileOutputStream. Everything is working fine but I want to separate each appended stream from file while reading it.
Here is how I created file and writing it in Android
FileOutputStream outputStream = service.openFileOutput("text.txt", Context.MODE_APPEND);
outputStream.write(measurement.toString().getBytes());
outputStream.close();
It is appending data successfully but when I am reading it I do not know how to find end point between appended strings.
Here is my code to read the string from file
StringBuilder total = new StringBuilder();
FileInputStream inputStream = service.openFileInput("text.txt");
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
Log.d(TAG, "File Size: "+total.length());
For future references, it is silly that I have not tried but thanks to #greenapps
I just had to add another write statement to append
FileOutputStream outputStream = service.openFileOutput("text.txt", Context.MODE_APPEND);
outputStream.write(measurement.toString().getBytes());
outputStream.write("\n".getBytes());
outputStream.close();
for reading saparated string I simply used split for java
String[] parts = total.toString().split("\n");
for(int i = 0; i < parts.length; i++) {
Log.d(TAG, parts[i]);
}
deleteFile("text.txt");
I have a text file called words.txt in folder raw within android res folder. I don't know how to get its path to make a new file with the given path. I use the code below, but seems it just doesn't work:
File file = new File("res/raw/words.txt").getAbsoluteFile();
String filePath = file.getAbsolutePath();
File wordFile = new File(filePath);
You can read the raw/words.txt as follows:
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(R.raw.words);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
Note: this code must be inside an Activity class, as this.getResources() refers to Context.getResources()
You can't write to your own app's res folder. It is not modifiable.
You can create a file here though:
http://developer.android.com/reference/android/content/Context.html#getFilesDir%28%29
If you want to use words.txt as a baseline, you can read from it and copy it to a modifiable file at runtime.
281~name~location~#time#room%
#time2#room2%
#time3#room3;
I need to delete the second line after the % in text file. But i dont know how to do that.
BufferedReader in = null;
out = null;
File sdCard = Environment.getExternalStorageDirectory();
File root = new File (sdCard.getAbsolutePath() + "/yourFile");
try {
InputStream instream = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(instream));
out = new PrintWriter(new File(root,"yournewFile));
String line; //a line in the file
while ((line = in.readLine()) != null) {
if (!Pattern.matches("^some pattern.*",line)) { //find the line we want to delete
//if it is not the line you want to delete then write it to new file
out.println(line);
}
}
in.close();
out.flush();
out.close();
File oldFile = new File (root,"/yourFile");
oldFile.delete();
File newFile = new File (root,"/yournewFile");
newFile.renameTo(oldFile);
}catch(Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
You should read old file and match it to the line you want to delete.if it is not the line you want to delete then write it to another file.thus you will get the new file with only that line missing which you wanted to delete.
you are done.hope it will help.
This is my code:
File root = Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/Bonbon info");
dir.mkdirs();
File f = new File(dir, "paket.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
br.skip(60);
int charactersRead = 0;
while ((line = br.readLine()) != null && charactersRead < 12) {
text.append(line);
text.append('\n');
charactersRead++;
}
}
catch (IOException e) {
}
final String URL = text.toString();
TextView tv = (TextView)findViewById(R.id.textView2);
tv.setText(text);
Reading is working, but i can't read only 12 characters, it reads trough the end of file, don't know why.
I'm guessing your file is relatively short.
You're calling BufferedReader.readLine(), which in an attempt to be efficient is sucking up a big chunk of the file stream rather than going through it character-by-character.
If you want that finer control over what you read, it's probably worth using an InputStream implementation straight up.