I'm writing to a file using the code below:
File file = new File(getCacheDir(), "cachefile");
FileOutputStream fos = new FileOutputStream(file);
StringBuilder cachetext = new StringBuilder();
Iterator bri = brands.iterator();
Iterator bli = brand_id.iterator();
while(bli.hasNext()) {
cachetext.append(bli.next() + "|" + bri.next() + System.getProperty("line.separator"));
}
fos.write(cachetext.toString().getBytes());
fos.close();
This works fine - no errors and the file ends up containing what I expect it to contain. When I go to read it via openFileInput(), however, I get an exception telling me that path separators are not allowed
FileInputStream fis = openFileInput(getCacheDir() + "/cachefile");
Fair enough, that contains a slash, but how else can I specify the path of the file I want to open? There must be a way to do this, of course, but I can't find answers via Google ('read', 'cache' and 'file' not being the most niche of terms ...) so I thought I'd try the human touch. Thanks in advance!
you do it pretty much the same way you created the output file:
FileInputStream fis = new FileInputStream(new File(getCacheDir(), "cachefile"));
Related
I am working on improving code coverage of my project and since there is a method I wrote to write file into android internalStorage by using the following code snippet from Android Developer website.
String FILENAME = "hello_file";
String string = "hello world!";
File testFile = new File(context.getFilesDir(), FILENAME);
FileOutputStream fos =new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();
My idea is to assert by reading the file and compare with hello world! and see if they matches to prove that my writing function works in unit test/ Android Instrumentation test. However, it not really straightforward for me to test this because of following
I don't know the path of the file from unit test aspect (JVM)
Not from Android instrumentation test perspective either.
What is the best practice to test this kind of IO functionality in Android? Should I even care about if the file had been created and put? Or I should simply just check if the fos from in not null?
FileOutputStream fos =new FileOutputStream(file);
Please kindly provide me the advices. Thanks.
I wouldn't test that the file is saved - this is not your system and Android AOSP should have tests for making sure the file actually saves. Read more here
What you want to test is if you are telling Android to save your file. Perhaps like this:
String FILENAME = "hello_file";
String string = "hello world!";
File testFile = new File(context.getFilesDir(), FILENAME);
FileOutputStream fos =new FileOutputStream(file);
public void saveAndClose(String data, FileOutputStream fos) {
fos.write(data.getBytes());
fos.close();
}
Then your test would use Mockito for the FOS and be:
FileOutputStream mockFos = Mockito.mock(FileOutputStream.class);
String data = "ensure written";
classUnderTest.saveAndClose(data, mockFos);
verify(mockFos).write(data.getBytes());
second test:
FileOutputStream mockFos = Mockito.mock(FileOutputStream.class);
String data = "ensure closed";
classUnderTest.saveAndClose(data, mockFos);
verify(mockFos).close();
This is perhaps a very naive question, but I cannot figure it out.
After writing to a file with FileOutputStream, I read the file again to get updated content, but only get the original content:
File avatarFile = new File(avatarFilePath);
if(avatarFile!=null){
if(!avatarFile.exists())
avatarFile.createNewFile();
fos = new FileOutputStream(avatarFile);
}
boolean result = scaledBitmap.compress(Bitmap.CompressFormat.JPEG,Constants.COMPRESSED_AVATAR_QUALITY, fos);
fos.flush();
fos.close();
//Now read again, but get the old avatar
File newfile = new File(avatarFilePath);
Picasso.with(context).load(newfile).into(imageView);
What is happening here?
Picasso is using the old cached image.
To bypass the memory cache, use following:
Picasso.with(context).load(newfile).skipMemoryCache().into(imageView);
My goal is very simple: I have a zip file in my assets folder and wish to get the last modified date of it.
I am able to access the file via the Assetmanager and create a file from it, but the modified date is the moment that file is written
AssetManager manager;
File checkFile = new File(source + "/" + "test.zip");
try
{
InputStream stream = manager.open(fileToCheck);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
FileOutputStream fos = new FileOutputStream(checkFile);
fos.write(buffer);
fos.close();
}
catch(IOException ioExc)
{
//stuff
}
long lastMod = checkFile.lastModified();
Date lastMod = new Date(lastMod ); //This is returning the current time,
//NOT the modified date of the file
Can anyone think of a way I could access the actual last modified date of the file in the assets folder? Any help would be greatly appreciated!
The easiest way is you can include the last modified date into that zip file (e.g, lastmod.txt). You can then unzip and read that file.
First I will say I've researched various solutions on StackOverflow and elsewhere and none have solved my issue. I'll admit that my knowledge in this area is somewhat lacking, so sorry for being all noobish.
I want to do what I assume to be a simple thing. My app creates a file on start up if it does not exist yet, and populates it with 30 "0.0", each on a different line (This is done successfully).
Then when you beat a level, the intent is to have the file read, the 0.0's and assign each one to an element of an array, assign the time remaining (for example, 2.5) to the appropriate spot ([0] for the first level, [1] for the second level, etc), and write it back to the file to keep track of how much time was remaining when the player beat each level.
The problem becomes, though it does write the score in the appropriate spot back into the file (I'm testing level 1 so in spot [0]), all of the other 0.0's become "null". So I know there is a mistake somewhere that I must not be seeing, and after several hours over several days of trying various solutions, I finally decided to ask for help here. This is the code below:
try {
String[] scoreArray = new String[30];
File sdCard = Environment.getExternalStorageDirectory();
File myFile = new File(sdCard.getAbsolutePath());
// myFile.createNewFile();
File file = new File(myFile, "RLGLscores.txt");
FileOutputStream fOut = new FileOutputStream(file);
String newLine = System.getProperty("line.separator");
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
FileInputStream fis = new FileInputStream(file);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fis));
String data = "";
int i = 0;
while ((data = myReader.readLine()) != null) {
scoreArray[i] = data;
i++;
}
myReader.close();
scoreArray[0] = timerStringFormat;
for (int j = 0; j < 30; j++) {
myOutWriter.write(scoreArray[j] + newLine);
}
myOutWriter.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
timerStringFormat is the String that holds the time remaining in the form of a String. Again I'm rather new to this. My game is nearly complete, I'm amazed I got as far as I have. But any help would be greatly appreciated.
Opening the file for writing truncates it to zero length. If you later try to read from it you just see an empty file.
To fix that, first read the contents, close the reader, and then open the output stream and write the modified contents back.
I'm working with a library and I need to get a file path stored at raw folder, so library methods create a FileInputStream, but I always get a FileNotFoundException from library methods.
So I have created a class and try:
String path = "android.resource://" +context.getPackageName () + "/" + "myFileName";
InputStream fis2 = getResources().openRawResource(R.raw.myFileName);
File f = new File(path);
fis2 and f are correctly created and I get no FileNotFoundException.
But when I try: FileInputStream fis = new FileInputStream(path); I get the FileNotFoundException.
I need to get a file path stored at raw folder
That is not possible, as it is not a file.
so library methods create a FileInputStream
Those library methods need to be adjusted to work with an ordinary InputStream. Then, use your fis2 InputStream.