I am using the below code for reading my file and it is working fine, but now I want to add new text to that file. Please help me
private void loadingDictionary() {
// TODO Auto-generated method stub
AssetManager mgr;
try{
mgr = getAssets();
InputStream is = mgr.open("dictinary.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder stringBuilder = new StringBuilder();
String ls = ",";
while(( line = br.readLine() ) != null){
stringBuilder.append( line );
stringBuilder.append( ls );
}
dictinaryLines = stringBuilder.toString();
dictLinesArray = dictinaryLines.split(ls);
}
catch(IOException e1){
}
}
I want to append the new text to the already existing data.
Please help me.
As far as I know you can not write to the assets folder. You should copy the data from your assets folder to the private of your application or even to the external storage, depending on how confident your data is.
See How to write files to assets folder or raw folder in android?
You can't. How ever you can append a string called by res/values/strings.xml. If you were doing a theme I would have suggested to declare a string in res/values.strings.xml, and append it, then have whatever app you wanted to change whatever text to read from strngs.xml.
Related
I am trying to read a file, but I get a NoSuchFileException. I know my code work, because it works in another program I have created, but it doesn't work now. Yes the directory is correct and there is a text file in the src folder. Please could someone tell me how to fix this.
String[] words = new String[5];
Path file = Paths.get("H:\\Varsity work\\Java Programming\\Programs\\HangMan\\build\\classes\\HangMan.txt");
InputStream input = null;
try {
input = Files.newInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String s = null;
while((s=reader.readLine())!=null) {
System.out.println(s);
}
input.close();
} catch(Exception e) {
System.out.println(e);
}
try using '/' instead of '\' , so no need to escape any chars and path string used as is.
In my program I made a saving and loading system for text files. The Save function works perfectly as intended but the Load gives a NullPointerException.
Here's the load function
String path = "C:\\Levels\\File.txt";
LevelHandler.loadLevel(path);
Here's the loadLevel function
public static void loadLevel(String file){
String level = LevelLoader.loadFileAsString(file);
//other, unimportant, code
}
And here's the loadFileAsString function
public static String loadFileAsString(String file){
StringBuilder builder = new StringBuilder();
try {
InputStream in = LevelLoader.class.getResourceAsStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = bufferedReader.readLine()) != null){
builder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
It's failing because it's looking for the file in the class folder regardless of what directory I pass in. How can I get the location of the .jar regardless of where the user places it on their computer?
you can get the .jar related location using ./
./ provides related path of your jar
The fix I came up with was to remove the InputStreamreader
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
This will be able to read files from any specified location on the computer, but still not from inside the jar. However it works perfectly fine with pretty much any other specified location.
I'm using Eclipse for a university project making an android app.
I'm having a problem with 1 thing:
I have created a class called TextFileHandler.
The idea is that the app instantiates TextFileHandler and uses the methods
to read and write the text files within the app with get methods simply
returning a string value and set methods writing new values to the text files.
When this class is instantiated the constructor creates a text file.
The methods are supposed to access the created text files and read and write them
but the problem is, once it creates the text files it can't seem to access them
and the app just crashes.
I have included the constructor and then directly after the method getMeds()
which just crashes every time. I'm not sure why it can't find the text files.
Any help would be appreciated.
constructor:
public TextFileHandler(Context ctx){
this.context = ctx;
//create the medicine text file
String medtext = "1#Med*2#Med*3#Med*4#Med*5#Med*";
try {
File file = new File("Medicine.txt");
//if the file doesn't already exist then create it
//this is to make sure the app saves state
if(!file.exists()){
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(medtext);
output.close();
}
} catch ( IOException e ) {
e.printStackTrace();
}
String remtext = "1a#000000*1b#000000*1c#000000*1d#000000*1e#000000*";
remtext += "2a#000000*2b#000000*2c#000000*2d#000000*2e#000000*";
remtext += "3a#000000*3b#000000*3c#000000*3d#000000*3e#000000*";
remtext += "4a#000000*4b#000000*4c#000000*4d#000000*4e#000000*";
remtext += "5a#000000*5b#000000*5c#000000*5d#000000*5e#000000*";
try {
File file = new File("Reminder.txt");
//if the file doesn't already exist then create it
//this is to make sure the app saves state
if(!file.exists()){
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(remtext);
output.close();
}
} catch ( IOException e ) {
e.printStackTrace();
}
}
get method:
public String getMeds() throws IOException{
FileInputStream in = openFileInput("Medicine.txt");
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
String ret = sb.toString();
return ret;
}
Create your file either privately (readable only by your app) using ctx.openFileOutput("Medicine.txt", MODE_PRIVATE) or publicly using new File(Environment.getExternalStorageDirectory(), "Medicine.txt").
To read the private file, use Context.openFileInput(String name).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
hi i just started learning android development and i'm trying to build an app that reads text from files.
i have been searching all over the internet but i don't seem to find the way to do so , so i have a few questions..
1.how to do this?
what is the preferred way to read a file line by line in android?
2.where should i store the file?
should it be in the raw folder or maybe in the assets folder?
so this is what i already tried: " (i think the problem may be with finding the file..)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filereader);
try {
// open the file for reading
InputStream fis = new FileInputStream("text.txt");
// if file the available for reading
if (fis != null) {
// prepare the file for reading
InputStreamReader chapterReader = new InputStreamReader(fis);
BufferedReader buffreader = new BufferedReader(chapterReader);
String line;
// read every line of the file into the line-variable, on line at the time
do {
line = buffreader.readLine();
// do something with the line
System.out.println(line);
} while (line != null);
}
} catch (Exception e) {
// print stack trace.
} finally {
// close the file.
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Depends on what you intend to do with that file. If your goal is only to read the file, then the asset folder is the way to go. If you want to store information in that file when you are done working with it, you should put it on the device.
If you choose option number 2, you need to decide if you want other applications to read the file. More information can be found at this address:
http://developer.android.com/training/basics/data-storage/files.html
Else, you can read/write directly to the device with the standard java procedure just like you described. Though, the filepath would probably be
"/sdcard/text.txt"
EDIT:
Here's some piece of code to get started with
FileInputStream is;
BufferedReader reader;
final File file = new File("/sdcard/text.txt");
if (file.exists()) {
is = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while(line != null){
Log.d("StackOverflow", line);
line = reader.readLine();
}
}
But it assumes that you know you've put the text.txt at the root of your sdcard.
If the file is in the assets folder, you have to do this:
BufferedReader reader;
try{
final InputStream file = getAssets().open("text.txt");
reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();
while(line != null){
Log.d("StackOverflow", line);
line = reader.readLine();
}
} catch(IOException ioe){
ioe.printStackTrace();
}
Your code looks good however, you should do your file reading asynchronously.
For the file path, it depends if it is a file that you bundle in your APK or a file that you download in the app data folder.
Depending on what version of android you are targeting, I would use try with resources...
to read from assets you can do this in an activity:
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
I'm trying to get save a text file from the internet into a folder in my res directory (res/files) so I can then read and interpret it. My android manifest has set the appropiate permissions but when I test it in the simulator it fails.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
Here's the method to get the file:
public void getTextFile(){
String path ="http://hullmc.org.uk/cjvize/test.txt";
URL u = null;
try {
u = new URL(path);
BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream()));
int i = 0;
String replicated = "";
do{
String str = in.readLine();
replicated = replicated + "/n" + str;
i++;
}while(i<85);
in.close();
}
catch(Exception e){
welcome.setText("Failed");
}
}
Can anyone suggest why this is not working? Many thanks!
This is working fine for me :
Use of class variable for View and Activity allow to keep code centralaized and shared, passing view as parameter, updated in constructor :)
1) Code to store the file locally
View newReport;
Activity reportActivity;
private void downloadFile(String fileUrl, String fileName) {
try{
InputStream is = (InputStream) new URL(fileUrl).getContent();
FileOutputStream output = reportActivity.openFileOutput(fileName, newReport.getContext().MODE_PRIVATE);
byte data[] = new byte[1024];
int count;
while ((count = is.read(data)) != -1)
output.write(data, 0, count);
output.flush();
output.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It saves the file on the internal storage.
Then to save a file from URL, just call:
downloadFile(myFileUrl, mySaveToFileName);
And to list your local files available:
String[] fileList = newReport.getContext().fileList();
for (String s : fileList){
System.out.println("File found : "+s);
}
Note: you do not require to save it locally to read it. If you prefer just to read it (to extract some info), let me know.
2) Code to "read and save to database", this should resolve:
// After InputStream declaration:
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
//TODO Update database row concatenating inputLine to existing text value.
}
in.close();
in=null;
is.close();
you can't save into the resource folder of your app. you can't even store files into the assets folder.
there aren't even such folders when you install the app - they are all zipped into the APK . the res folder is a special one too, because each file there also creates a constant in the "R.java" file, so that it would be easier to reach and use. you can't reach such a thing when it's dynamic...
what you can do is to choose the right folder for you (read here), and download the file into there, using something like this :
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fullFilePath);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1)
output.write(data, 0, count);
//todo close streams and handle exceptions
if you use Apache commons library, you could minimize the code to just one line:
IOUtils.copy(new BufferedInputStream(url.openStream()), new FileOutputStream(fullFilePath));