I am creating an XML file from my Database and storing it in Internal storage. I require data from XML file into a single string. For which, i am using the following method.
BufferedReader br;
try {
br = new BufferedReader(new FileReader(new File(pathDAR)));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line.trim());
String temp = sb.toString().substring(38);
Log.v("XML TO String", "" + temp);
Log.v("Lengths : ", "" + temp.length() + " " + sb.length());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have been getting string in the Log, but it seems to be stopping abruptly in the middle.
For e.g. I am supposed to get records string like this. Beginning and ending with database tag.
<database name="DAR.db"><table name="DARWorkDetails"><row><col name="id">1</col><col name="date">05-28-2013</col><col name="visited_city_ID">1264</col><col name="employee_ID">107</col><col name="work_type_ID">1</col><col name="name">null</col><col name="customer_Id">null</col><col name="customer_type_ID">null</col><col name="sub_customer_id">null</col><col name="reason_ID">14</col><col name="reason">ABM SM MEETING</col><col name="remarks">gfhii</col><col name="work_with">211,162</col><col name="IsCustomer">N</col><col name="created_by">107</col><col name="position_id">72</col><col name="designation_Id">3</col><col name="submit_date">05-28-2013</col><col name="IsFinal">null</col></row></table></database>
Instead i have been getting string like this :
<database name="DAR.db"><table name="DARWorkDetails"><row><col name="id">1</col><col name="date">05-28-2013</col><col name="visited_city_ID">1264</col><col name="employee_ID">107</col><col name="work_type_ID">1</col><col name="name">null</col><col name="customer_Id">null</col><col name="customer_type_ID">null</col><col name="sub_customer_id">null</col><col name="reason_ID">14</col><col name="reason">ABM SM MEETING</col><col name="remarks">gfhii</col><col name="work_with">211,162</col><col name="IsCustomer">N</col><col name="created_by">107</col><col name="position_id">72</col><col name="designation_Id">3</col><col name="submit_date">05-28-2013</col><col name="IsFinal">null</co
The String is stopping in the middle. For the sake of example i have only put small example string above. In reality my database has multiple records and i have counted length of the string to around 15640, before abrupt end of the string.
Are there any limitations with StringBuilder in regards to storing characters? I suppose there is memory issue since i have been able to get string fully for records fewer than 10. Problem seems to be arising when records go into upwards of 10. Any help in understanding of solving this issue would be much appreciated.
Please check
It may happen your output is perfect but your Log cat is not displaying it whole.
Log.v("XML TO String", "" + temp);
Log.v("Lengths : ", "" + temp.length() + " " + sb.length());
See reference
I created this class to read strings from a xml file saved in internal storage device, it returns a list , if you want the whole extended string you only need concatenate to link together, if doesn't found the file return an empty list this is all you need to read XML files and parse to Strings, I hope to help!
public class readXMLFile {
private String filePath = "FileStorage";
private String fileName = "File.xml";
private final String tag = "Internal Read Persistence";
File internalFileData;
public readXMLFile() {// default constructor
}
public File getXMLFile(Context context){
File directory = null;
ContextWrapper cw = new ContextWrapper(context);
directory = cw.getDir(filePath, Context.MODE_PRIVATE);
internalFileData = new File(directory, fileName);
if(internalFileData.exists()){
Log.i("ReadXMLFile","File returned");
return internalFileData;
}
else{
Log.i(tag,"the file doesn't exists!");
return null;
}
}
public List<String> readFile(Context context) {
List<String> l = new LinkedList<String>();
try {
File directory = null;
ContextWrapper cw = new ContextWrapper(context);
directory = cw.getDir(filePath, Context.MODE_PRIVATE);
internalFileData = new File(directory, fileName);
if (internalFileData.exists()) {
Log.i("Internal Data", "the root exists!!");
try {
FileInputStream fis = new FileInputStream(internalFileData);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
l.add(line);
}
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
Log.i(tag, "Exception closing persistence connection");
}
} catch (Exception e) {
Log.wtf("Fatal Exception", "Exception: " + e.getMessage());
}
} else {
Log.i(tag, "File doesn't exists");
return l;//return empty list
}
} catch (Exception e) {
Log.wtf(tag, "Exception DATA READING: " + e.getMessage());
return l;
}
Log.i(tag, "file found return");
return l;
}
}
Related
i have written some code that takes an ip address inputted from a text file full of addresses and converts these to the physical location
however occasionally the results will give a null pointer exception - kinda to be expected due to the text file being inputted sometimes not being 100% formatted correctly, however when i have over a million addresses the null pointer exception can be a bit annoying stopping my program haha - can i code in such a way which catches the exception and just carries on ?
public convert() {
// System.out.println("in test");
Locate obj = new Locate();
String file = "Bitcoin_IP.txt";
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// System.out.println(line);
ServerLocation location = obj.getLocation(line);
System.out.println(location);
try {
String filename = "Locations.txt";
try (FileWriter fw = new FileWriter(filename, true)) {
fw.write(location + "\n");
}
} catch (NullPointerException ioe) {
System.err.println("NullPointerException: " + ioe.getMessage());
}
}
} catch (IOException ex) {
Logger.getLogger(Locate.class.getName()).log(Level.SEVERE, null, ex);
}
}
You're already catching NPE for some of the code, so if you are still getting those particular exceptions they must be originating here:
ServerLocation location = obj.getLocation(line);
So try this:
try {
ServerLocation location = obj.getLocation(line);
System.out.println(location);
String filename = "Locations.txt";
try (FileWriter fw = new FileWriter(filename, true)) {
fw.write(location + "\n");
}
} catch (NullPointerException ioe) {
System.err.println("NullPointerException: " + ioe.getMessage());
}
I'm looking to create a find and replace java application which prompts users to call to a text file, print it out to a new file, ask user for a search word or phrase and a word to replace that searched word with. Here is the code I have so far. I can read the contents from the first file just fine but cannot write the contents from the first file to another. This is all done within a GUI code below
String loc = jTextField1.getText(); //gets location of initial file or "source"
String file = jTextField4.getText(); //new file path
String find = jTextField2.getText(); //find word inputted by user
String word = jTextField3.getText(); //replace "find" with word inputted by user
String line = null;
try {
BufferedReader br = new BufferedReader(new FileReader(loc));
while ((line = br.readLine()) !=null)
} catch (FileNotFoundException ex) {
Logger.getLogger(Assign6GUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Assign6GUI.class.getName()).log(Level.SEVERE, null, ex);
}
To write content to a file you need to use BufferedWriter
public static void writetoFile(String str, String FILE_PATH, String FILENAME ) {
BufferedWriter writer = null;
try {
File file = new File(FILE_PATH);
// if file doesnt exists, then create it
if (!file.exists()) {
file.mkdir();
}
file = new File(FILE_PATH + FILENAME);
file.createNewFile();
writer = new BufferedWriter(new FileWriter(file));
writer.write(str);
} catch (IOException e) {
LOGGER.debug(e);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (Exception e) {
LOGGER.debug(e);
}
}
}
to replace words in a string you should use the replace function in java
String str = someString.replace("OldText", "NewText");
I'm new to android studio and I have this textview which shows the data that is stored to my text file. If I click the button, it should read the data inside the text file, add integer and the sum should replace the existing data in the text file. However when I return to the activity which show's the textView with the new data in the text file, it does not change.
Here's the code for my textView
txt_stars = (TextView) findViewById(R.id.txtStars);
try {
FileInputStream fileInputStream = openFileInput("Stars.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String star;
while ((star=bufferedReader.readLine()) != null){
stringBuffer.append(star);
}
txt_stars.setText(stringBuffer.toString());
}
catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And the code for the button
Integer stars, totalStars;
public void onClick(DialogInterface dialog, int whichButton) {
try {
FileInputStream fileInputStream = openFileInput("Stars.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String star;
while ((star = bufferedReader.readLine()) != null) {
stringBuffer.append(star);
}
stars = Integer.parseInt(stringBuffer.toString());
totalStars = stars + 50;
//is this acceptable?
FileOutputStream fileOutputStream = openFileOutput("Stars.txt", MODE_PRIVATE);
fileOutputStream.write(totalStars.toString().getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent nextForm = new Intent(".MainActivity");
startActivity(nextForm);
}
And also, where can I find the created text file in my phone so that I can assure that the text file is created? I'm using Android studio 1.5.1 and running the app to my phone.
I have this in my manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Is there anything I should do to locate and create the text file?
I have been stuck here for days. Please help me.
Thanks a lot!
This might be due to a FileNotFoundException when you'd read the file in the save method. When you try to update the file and write into it, you don't separate the try/catch methods so you might have an exception at the reading part which prevents to continue the script and to update the file. Maybe this was printing in the Logcat but you haven't take a look.
So I'd suggest you to check if the file already exists and to separate the reading/writing parts.
When you first read the file to display it in TextView, just check if it's created to avoid a background exception:
File f = new File(getFilesDir().toString() + "/stars.txt");
Log.v("", "Does the file exist? " + f.exists());
if (f.exists()) {
readFile();
}
You can see here where the file should be stored (in getFilesDir()). The path is choosen by default when you use openFileInput(String), and it's:
data/data/com.package.name/files/
You have to keep in mind that you actually don't create /files folder in your code and for example, I had to create it myself to work with the above method. (This can be only my device but you'd be aware this can prevent the file to be created.)
Now, there is no big changes in your reading method and this is how it looks:
private void readFile() {
try {
FileInputStream file = openFileInput("stars.txt");
InputStreamReader inRead = new InputStreamReader(file);
BufferedReader buffReader = new BufferedReader(inRead);
StringBuffer stringBuffer = new StringBuffer();
String star;
while ((star = buffReader.readLine()) != null) {
stringBuffer.append(star);
}
inRead.close();
file.close();
txt_stars.setText(stringBuffer.toString());
} catch (Exception e) {
Log.e("ReadFile", e.toString());
}
}
Obviously, this method is called only if the previous check returns true. You have to do the same when the Button is clicked: check if it exists -> if yes, get the content, do your stuff (add, sum, etc) and write into it -> if not, just create it by writing into it.
Something as follows will work:
public void writeFile(View v) {
File f = new File(getFilesDir().toString() + "/stars.txt");
Log.v("", "Does it exist? " + f.exists());
String result = "";
if ( f.exists() ) {
try {
FileInputStream file = openFileInput("stars.txt");
InputStreamReader inRead = new InputStreamReader(file);
BufferedReader buffReader = new BufferedReader(inRead);
StringBuffer stringBuffer = new StringBuffer();
String star;
while ((star=buffReader.readLine()) != null) {
stringBuffer.append(star);
}
result = stringBuffer.toString();
inRead.close();
file.close();
} catch (Exception e) {
Log.e("WriteFile", "--- Error on reading file: "+e.toString());
}
} else {
// get the user's star or whatever
result = editRating.getText().toString();
}
Log.v("WriteFile", "--- Read file returns: " + result);
stars = Integer.parseInt(result);
totalStars = stars + 50;
try {
FileOutputStream fileOut = openFileOutput("stars.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fileOut);
outputWriter.write(String.valueOf(totalStars));
outputWriter.close();
fileOut.close();
// display file saved message
Toast.makeText(getBaseContext(), "File saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(" WriteFile", e.toString());
}
}
At this point, when you returned to the previous activity, you should be able to see the changes.
However, in order to see the file in your storage, you unfortunately must to have a rooted device, else you'll see an empty folder. Then finally, you'd avoid to restart the Activity. You should finish the editing one, this will come back to the previous one, and you just have to call readFile() in onResume() instead of onCreate(). It will update the new content into the TextView.
Have you tried on updating textview before starting new Activity? Example:
txt_start.setText(""+totalStars);
I am trying to Edit a existing file which is in my R.raw folder
i am able to read the file
but when i run the write function it is not working .
public void tofile(View v){
BufferedWriter bw=null;
FileWriter fw =null;
try {
String path = ("/Page2/res/raw/text.txt");
File file = new File(path);
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write("hello");
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
i even tried
fw = new FileWriter(file,true);
if i add toast between even line it seems to get stuck at
fw = new FileWriter(fw);
You can't able to Write
As #CommonsWare said you can't write on resources but you could use internal storage using openFileOutput and openFileInput and BufferedReaders and BufferedWriters. You can check it here
from the answer of #rodkarom in the following link
Write to a Text File Resource in Android
and #Andro Selva says same thing in the following link
How to write a file in Android to the raw folder?
you can able to read the content from the textfile which is present in the res/raw folder dude
read the file from res folder
public String readStringFromResource(Context ctx, int resourceID) {
StringBuilder contents = new StringBuilder();
String sep = System.getProperty("line.separator");
try {
InputStream is = ctx.getResources().openRawResource(R.raw.trails);
BufferedReader input = new BufferedReader(new InputStreamReader(is), 1024*8);
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(sep);
}
}
finally {
input.close();
}
}
catch (FileNotFoundException ex) {
Log.e(TAG, "Couldn't find the file " + resourceID + " " + ex);
return null;
}
catch (IOException ex){
Log.e(TAG, "Error reading file " + resourceID + " " + ex);
return null;
}
return contents.toString();
}
check it and inform
I am trying to display images inside my HTTP Web Server but I'm unable to. I can display the HTML. I think it is something to do with the way I handle my IO (input and output streams). There's probably a lot of mistakes in there that I haven't noticed.
import java.io.* ;
import java.net.* ;
import java.util.Properties;
public class HTTPThread extends Thread
{
private Socket socket = null;
private Properties config = null;
private String root = "";
public HTTPThread(Socket s, Properties config)
{
this.socket = s;
this.config = config;
this.root = this.config.getProperty("root");
}
public void run()
{
// InputStream in = null;
OutputStream out = null;
try
{
out = socket.getOutputStream();
PrintWriter writer = new PrintWriter(out, true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String request = reader.readLine();
writer.println("HTTP/1.1 200 OK");
writer.println("Content-Type: text/html");
writer.println();
// Search for filename
int slash = request.indexOf("/"); //find first occurrence of slash
int emptySpace = request.indexOf(" ", slash); //find first space after slash
String filename = request.substring(slash, emptySpace); //return filename
// writer.println("<b>" + filename + "</b>");
String pathname = "";
try
{
pathname = (filename == "/") ? root + filename : root;
// System.out.println(filename);
URL url = new URL(pathname);
URLConnection urlc = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
urlc.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
writer.println(line);
}
in.close();
}
catch (MalformedURLException e)
{
System.err.println("Don't know about host: " + pathname);
System.exit(1);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for "
+ "the connection to: " + pathname);
System.exit(1);
}
// reader.close();
writer.close();
socket.close();
}
catch(IOException e)
{
System.out.println("Error: " + e);
}
finally
{
try
{
// in.close() ;
out.close() ;
socket.close();
}
catch(IOException e)
{
System.out.println("Error: " + e);
}
}
}
}
Are you trying to write some sort of proxy server that takes external URL from the request and returns the contents? Well, there are several issues with your code:
writer.println("HTTP/1.1 200 OK");
writer.println("Content-Type: text/html");
When browser sees the above, it assumes whatever is returned is HTML. Rendering binary image as HTML will clearly fail. Which leads us to this:
String line;
while ((line = in.readLine()) != null)
{
writer.println(line);
}
in.close();
In the loop above you are reading some external URL line-by-line (in text mode) and forwarding it to original client. This works for HTML (which is text-based) but will fail for any image (binary). You must use InputStream/OutputStream instead.
And small thing at the end:
pathname = (filename == "/") ? root + filename : root;
Do not compare strings using == operator, replace it with:
pathname = (filename.equals("/")) ? root + filename : root;
As a final note, consider using servlet container like Tomcat or Jetty, which will release you from HTTP-handling code and provide more high-level constructs.