Is it possible to read a textfile on sdcard during runtime of an UIautomator test? As in an android application, using getExternalDirectory() etc. to create a File-object pointing to the actual file. Is it possible to send a command using getRuntime().exec("cmd"), if so, how? Or is there an easier way to simply access the device:s sdcard and read a file into the test?
The goal is to throughout the test send parameters to the test. So the test will perform certain actions, then continously look for a change on a file on the devices sdcard, and if so, read that line, and continue to perform actions. So therefor a way to read a file, and check certain things, is needed.
Or is there perhaps another way to pass information into the test during runtime? I know it can be done at the start of the testrun, but not during testrun.
I use below code inside uiautomator code to read text files.instead of
public void FileRead(String file_location) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file_location));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
//you can do whatever you want here or return String
} finally {
br.close();
}
}
Related
I would like to compare content of .txt file that i have in my assets folder with some text on the screen.
Usually when I assert text on the screen I use:
onView(withId(R.id.someId)).check(matches(withText("String")));
is ther any easy way so i can assert it from file?
Also, if you want to shorten your assertions and actions when using Expresso, check this library: https://github.com/SchibstedSpain/Barista (disclaimer: I'm a contributor).
It contains a set of quick actions and assertions that make the tests much more readable.
Here is a code to read text from text file.
StringBuilder buf=new StringBuilder();
InputStream json=getAssets().open("book/contents.json");
BufferedReader in=
new BufferedReader(new InputStreamReader(json, "UTF-8"));
String str;
while ((str=in.readLine()) != null) {
buf.append(str);
}
in.close();
now compare your string from assets to you screen text.
buf.toString().equals("your text here");
Is it possible to load strings.xml from sd card instead of application res/values/... Search on the web but didn't find any tutorials. My thought is download the xml to sd card then save the strings element to an array.
public void stringsxml(){
File file = new File(Environment.getExternalStorageDirectory()
+ ".strings.xml");
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
String data= contents.toString();
}
Well, actually it is semi-possible, but you have to create a derivate LayoutInflater which will replace string codes with thus read strings.
I have documented my attempts and failings together with initial implementation here.
Summary: simple strings work, string arrays do not
No, this is not possible. Check Android decoumentation about resources:
The Android SDK tools compile your application's resources into the application binary at build time. To use a resource, you must install it correctly in the source tree (inside your project's res/ directory) and build your application.
Resources are built-in into the application binary and you can't read them from a file.
I've been researching about how diablo 2 dynamically generates loot, and I thought it'd be fun to create a fun app that will randomly generate items using this system.
I currently have code which I believe should read the entire txt file, but it's not parsed.
It looks like:
private void itemGenerator() {
int ch;
StringBuffer strContent = new StringBuffer("");
InputStream fs = getResources().openRawResource(R.raw.treasureclass);
// read file until end and put into strContent
try {
while((ch = fs.read()) != -1){
strContent.append((char)ch);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
An example in the text file would look something like:
Treasure Class Item1 Item2 Item3
tc:armo3 Quilted_Armor Buckler Leather_Armor
tc:armo60a Embossed_Plate Sun_Spirit Fury_Visor
tc:armo60b Sacred_Rondache Mage_Plate Diadem
So what I'm thinking right now is putting each row into an array with StringTokenizer delimited by \n to get each row. Then somehow do it again with tab-delimited for each item in the array and put it into a 2D array?
I haven't coded it yet because I think there's a better way to implement this that I haven't been able to find, and was hoping for some helpful input on the matter.
For anyone actually interested in knowing how the item generation works, their wiki page, http://diablo2.diablowiki.net/Item_Generation_Tutorial, goes very in-depth!
I think you are facing problem in distinguishing between each lines that are read-out from file. In order to read the file line-by-line you should change your code as below:
InputStream fs = getResources().openRawResource(R.raw.treasureclass);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
String line = null;
while((line = br.readLine()) != null){
Log.i("line", line);
//split the content of 'line' and save them in your desired way
}
I cannot understand why this keeps crashing with a memory error:
server = new URL("http://-link cannot be supplied-");
BufferedReader reader2 = read(server);
line = reader2.readLine();
StringBuilder bigString = new StringBuilder("");
while(line!=null) {
bigString.append(line);
reader2.readLine();
}
the file is not -that- big 7000 odd lines # 240,031 bytes on disk.
Basically what i need to do is to tell wether the file contains a small string (a postcode) the file is basically a list of postcodes.
What is the best way to read this in? as obviously what i am doing is not working at all :D
Your while loop never ends!
while(line!=null) {
bigString.append(line);
line = reader2.readLine();
}
should work.
I'm trying to develop a small application, where I was given a JSON file, and I have to extract data from it. As I understood a JSON object takes a string argument, thus I'm trying to access a file and write the data from it to a string.
I've placed that file in a "JSON file" folder, and when I try to read the file, it throws me a file not found exception.
I've tried several ways to find a path to that file, but every attempt was for vain.
It might be that I'm extracting the path wrong, or might be something else, please help me.
Thanks in advance.
here is the code of finding the path:
try
{
path = Environment.getRootDirectory().getCanonicalPath();
}
catch (IOException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
File jFile = new File(path + /"JSON file/gallery.json");
here is the code for reading from a file :
String str ="";
try
{
BufferedReader in = new BufferedReader(new FileReader(jFile));
while ((str += in.readLine()) != null)
{
}
in.close();
}
catch (IOException e)
{
e.getMessage();
}
return str;
Here more specification:
I want to take the data from the file in order to do that : JSONObject(jString).
when I extract the path of json file I create a file with the path and pass it to the function that reads from the file, and there it throws me a file not found exception, when I try to read from it.
The file does exists in the folder (even visually - I've tried to attach an image but the site won't let me, because I'm new user)
I've tried to open the file through the windows address bar by typing the path like that:
C:\Users\Marat\IdeaProjects\MyTask\JSON file\gallery.json and it opens it.
if you store it in the assets folder you can access it by using
InputStream is = context.getResources().getAssets().open("sample.json");
You can then convert it to a String
public static String inputStreamAsString(InputStream stream)
throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
EDIT
You need to put the file in the device, if it is on your computer, it is not accessible from your device. There are some ways to do that, and one of them is to put it in the res/ dir of your application. Please refer to the documentation to see how to do that.
Debug it. I'm pretty sure it will be very easy to find. To start with, look for the following:
Print the path before you create the file, e.g. Log.d("SomeTag", path + "/JSON file/gallery.json")
Observe the full exception details. Maybe there is another problem.
Explore the folders and see if the file exists (in eclipse: window -> show view -> other -> android -> file explorer.
You will probably observe the problem and be able to fix it. If not, post here a question with more details, including the results of those trials.
BTW, GetgetRootDirectory() returns the root directory of android, that's not what you want (you don't have RW permissions there) you probably want to get the applcation directory, you can see how to get it here, in the question I asked a few month ago. But since you didn't give us those details, it will be hard to help you more then that.