I am currently reading a dictionary.png (which is a text file) into a buffer.
.png to make android think it is compressed.
InputStream is = getResources().openRawResource(R.raw.dictionary);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF8"));
String next;
while ((next = br.readLine()) != null) {
//Add the string next to a map or whatever
}
} catch (Exception e) {
//Something nasty happened
}
i'm not very familiar with HashMaps but i want to read the files from the dictionary into a hash map.
Any help would be appreciated.
An example that does something similar to what you're asking about: Using HashMap to map a String and int
Related
This is related to a situation I find myself in working with saving text files in Unity on Android, then reading them in native Android.
One of the files we read is a HMACMD5 signature, created with the code,
byte[] bData = System.Text.Encoding.UTF8.GetBytes (data);
byte[] bKey = System.Text.Encoding.UTF8.GetBytes (key);
using (HMACMD5 hmac = new HMACMD5(bKey)) {
byte[] signature = hmac.ComputeHash (bData);
return System.Convert.ToBase64String (signature);
}
And then written to the phone with,
public static void SaveText (string path, string data) {
using (FileStream fs = new FileStream(path, FileMode.Create)) {
using (StreamWriter sw = new StreamWriter(fs)) {
sw.Write (data);
}
}
}
The other string we're saving is a JSON string dump. The signature has a newline character at the end of the string, but the JSON string doesn't. I know I can manually add one, but this question is about reading the accurate file contents.
On Android, based on previous SO answers, I read the file with,
String readFile(File file) {
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append("\n");
}
br.close();
}
catch (IOException e) {
MyLogger.e(LOG_TAG, "Error opening file " + file.getPath(), e);
}
return text.toString();
}
I'm manually adding the newline character after every line, but if I do this, I don't accurately read the JSON file, which doesn't have a newline character at the end. If I don't add the newline, I don't accurately read the signature file, which does.
You better then do not use readLine() but read().
I'm a new student working on an android application. The application is almost done and works fine.
The app uses a property list to generate it's content. At this moment it uses a .plist file located in the assets folder. Ideally I want this .plist file to be retrieved from an URL. However i'm stuck on this part for a few days now.
Could you please advise me in how to realise retrieving and using the file from an URL. Any advice is welcome!
In my code we see how I currently read the .plist file. I don't think the parsing of the response is required info for my question:
public class PListHelper {
/**
* PlayList reader from assets
*
* #return string of p-list file
*/
public static String readPlayListFromAssets(Context context) {
StringBuffer sb = new StringBuffer();
BufferedReader br=null;
try {
br = new BufferedReader(new InputStreamReader(context.getAssets().open("restaurant.plist")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException ex) {
ex.printStackTrace();
}
}
Log.i("Main", "input: "+sb.toString());
return sb.toString();
}
Have a look at URLConnection
Also, in the future, avoid using .plist as it something specific to ios and osx. By using another format (like json) you won't have to implement your own parsing.
I have a working filereader for a text file in my Raw Dir. The user should see the text file in the same format as I have formatted it in word but when the application is played, the text file is tightly grouped together with no paragraphs.
This is the file reader method below, as I said it does work but I just want the format to be as I have made it.
Your advice and guidance will be greatly appricated
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_support);
InputStreamReader isr = new InputStreamReader(this.getResources().openRawResource(R.raw.supporttext));
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String s;
try{
while ((s = br.readLine()) != null){
sb.append(s);
}
}catch (IOException e) {
e.printStackTrace();
}
TextView tv = (TextView)findViewById(R.id.supporttxt);
tv.setText(sb.toString());
From BufferedReader#readline java doc :
A String containing the contents of the line, not including any line-termination characters
So using readline strips the line-termination characters, that's why you do not see them in your Text View. You can add them back like this :
try{
while ((s = br.readLine()) != null){
sb.append(s);
sb.append("\n");
}
}catch (IOException e) {
e.printStackTrace();
}
Also, you should probably use getText instead of openRawResource
I want to read a txt file that contains a lot of different chunks of text separated by a string. In xcode this is pretty easy and i just use.
self.Array = [text componentsSeparatedByString: #"NEWSTRING"];
I don't seem to get this to work in android though, I can read in the whole text and put it into an array but it doesn't get separated so its just one long text.
I am using this code
AssetManager mngr;
String line = null;
boolean skillcheck = false;
StringBuffer sb = new StringBuffer(0);
String[] bb = null;
tester = new ArrayList <String>();
try {
mngr = getAssets();
InputStream is = mngr.open("mytext.txt");
InputStreamReader sir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(sir);
while((line=br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
tester.add(sb);
br.close();
} catch (IOException e1) {
}
Any good ways to do this?
You can use String.split method
String[] result = text.split("sometext");
For your acknowledgement
String.split returns the array of strings computed by splitting this
string around matches of the given regular expression
You should use StringTokenizer.
StringTokenizer sTok=new StringTokenizer(stringVariable, "newString");
while(sTok.hasMoreTokens())
System.out.println(sTok.nextToken());
stringVariable is the file contents and newString is the delimiter string.
EDIT
The second parameter of the StringTokenizer's constructor is the delimiter. It can be a new line \n or comma , or whatever you want.
I'm trying to figure out why special characters in a JSON feed (that looks completely fine when viewed in a browser) will break when used in my Android code. Characters with accent marks, ellipsis characters, curly quote characters and so on are replaced by other characters--perhaps translating it from UTF-8 down to ASCII? I'm not sure. I'm using a GET request to pull JSON data from a server, parsing it, storing it in a database, then using Html.fromHtml() and placing the contents in a TextView.
After much experimentation, I narrowed down possibilities until I discovered the problem is with the Ignition HTTP libraries (https://github.com/kaeppler/ignition). Specifically, with ignitedHttpResponse.getResponseBodyAsString()
Although that's a handy shortcut, that one line results in the broken characters. Instead, I now use:
InputStream contentStream = ignitedHttpResponse.getResponseBody();
String content = Util.inputStreamToString(contentStream);
public static String inputStreamToString(InputStream is) throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total.toString();
}
Edit: Adding more detail
Here is a minimum test case to reproduce the issue.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
activity = this;
instance = this;
String url = SaveConstants.URL;
IgnitedHttpRequest request = new IgnitedHttp(activity).get(url);
InputStream contentStream = null;
try {
IgnitedHttpResponse response = request.send();
String badContent = response.getResponseBodyAsString();
int start = badContent.indexOf("is Texas");
Log.e(TAG, "bad content: " + badContent.substring(start, start + 10));
contentStream = response.getResponseBody();
String goodContent = Util.inputStreamToString(contentStream);
start = goodContent.indexOf("is Texas");
Log.e(TAG, "good content: " + goodContent.substring(start, start + 10));
} catch (IOException ioe) {
Log.e(TAG, "error", ioe);
}
}
In the log:
bad content: is Texasâ good content: is Texas’
Update: either I'm crazy, or the problem only occurs in the clients' production feed, not their development feed, although the contents look identical when viewed in a browser--showing "Texas’". So perhaps there's some wonky server configuration required to cause this issue... but still, the fix for this issue when it occurs is as I outlined. I do not recommend using response.getResponseBodyAsString();