• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to read a file in a string

 
muhammad sami
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i am trying to read a file in a string so that i can serach for particuler words but the problem is that the file can contain special characters like " (double quotes ) and single quotes so the program would give errors is there any way around ,can any one help in this regards,or send me a sample code
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simplest thing would be to create a BufferedReader and read the file line by line, or character by character, aggregating to a StringBuffer that you can then turn into a String.
Why are you expecting quotes to cause a problem?
Bill
 
Md Fizal
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by muhammad sami:
i am trying to read a file in a string so that i can serach for particuler words but the problem is that the file can contain special characters like " (double quotes ) and single quotes so the program would give errors is there any way around ,can any one help in this regards,or send me a sample code
 
Md Fizal
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by muhammad sami:
i am trying to read a file in a string so that i can serach for particuler words but the problem is that the file can contain special characters like " (double quotes ) and single quotes so the program would give errors is there any way around ,can any one help in this regards,or send me a sample code

Try this
FileInputStream fis = new FileInputStream("a.txt");
String str="";
int i;
while(i=fis.read()!=-1)
str+= String.valueOf((char)i);
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ewwwww! thats really inefficient.

It creates and discards String objects at the rate of one per character. This is what StringBuffer was made for.

Bill
 
Dana Hanna
Ranch Hand
Posts: 227
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even that duplicates effort - just use the BufferedReader created from a FileReader!!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!