Reading file from assets throwing FileNotFoundException - android

I'm using the following code:
public void readLevel(int line){
AssetManager am = this.getAssets();
InputStream is = null;
try {
is = am.open("levelinfo.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scanner = new Scanner(is);
scanner.useDelimiter(",");
String skip;
for(int i = 1; i < line; i++){
skip = scanner.nextLine();
}
levelData = new ArrayList<Integer>();
while(scanner.hasNextInt()){
levelData.add(scanner.nextInt());
}
}
The code is giving a FileNotFoundException. I've seen some similar problems, but I'm not quite sure how to solve it. The file is a text file inside the assets folder. Any help is appreciated
Andy

Try out this way:
AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("levelinfo.txt");
if ( inputStream != null)
Log.d(TAG, "It worked!");
} catch (IOException e) {
e.printStackTrace();
}

Related

{Android} How can I open my text file from uri?

I want to create an app that will be capable of opening text files from uri. At the time, I have this code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_view_layout);
final Uri uri = getIntent() != null ? getIntent().getData() : null;
StringBuilder text = new StringBuilder();
InputStream inputStream = null;
}
how can I make it read the whole file ?
Best regards, Traabefi
I've done some magic with this and it's working very good :D Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_view_layout);
final Uri uri = getIntent() != null ? getIntent().getData() : null;
InputStream inputStream = null;
String str = "";
StringBuffer buf = new StringBuffer();
TextView txt = (TextView)findViewById(R.id.textView);
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
if (inputStream!=null){
try {
while((str = reader.readLine())!=null){
buf.append(str+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
txt.setText(buf.toString());
}
}
Create a new File object from Uri's path and pass it to the FileInputStream constructor:
try {
inputStream = new FileInputStream(new File(uri.getPath()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
yourTextView.setText(s.hasNext() ? s.next() : "");
I got the InputStream to String technique from this answer by Pavel Repin.
Don't forget to close your stream.

reading Text from file in assets

i have an text file in my assets folder called test.txt. It contains a string in the form
"item1,item2,item3
How do i read the text into and array so that I can then toast any one of the three items that are deliminated by a comma
After reading post here the way to load the file is as follows
AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("test.txt");
But cant work out how to get into an array
your help is appreciated
Mark
This is one way:
InputStreat inputStream = getAssets().open("test.txt");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] myArray = TextUtils.split(byteArrayOutputStream.toString(), ",");
Here is a sample code :
private void readFromAsset() throws UnsupportedEncodingException {
AssetManager assetManager = getAssets();
InputStream is = null;
try {
is = assetManager.open("your_path/your_text.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
try {
while ((line = reader.readLine()) != null) {
//Read line by line here
}
} catch (IOException e) {
e.printStackTrace();
}
}

How to return file object from assets in Android?

I want to return file object from assests folder. In Similar questions's response, it's returned InputStream class object, but I don't want to read content.
What I try to explain, there is an example.eg file in assests folder. I need to state this file as File file = new File(path).
Try this:
try {
BufferedReader r = new BufferedReader(new InputStreamReader(getAssets().open("example.csv")));
StringBuilder content = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
content(line);
}
} catch (IOException e) {
e.printStackTrace();
}
As far as I know, assets are not regular accessible files like others.
I used to copy them to internal storage and then use them.
Here is the basic idea of it:
final AssetManager assetManager = getAssets();
try {
for (final String asset : assetManager.list("")) {
final InputStream inputStream = assetManager.open(asset);
// ...
}
}
catch (IOException e) {
e.printStackTrace();
}
You can straight way create a file using InputStream.
AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}

How to read a text file character by character in android?

I would like to know how can I read a text file from assets character by character.
For example, if I have this file "text.txt" and inside of it "12345", I would like to read all numbers one by one.
I've already looked for this but I can't find any solution.
Thanks.
Use getAssets().open("name.txt") to retrieve an InputStream on assets/name.txt, then read it in as you wish.
Thanks CommonsWare for your answer :) Along with my link where I did replied to Eric, I did add your piece of code and here is the result (fully working):
AssetManager manager = getContext().getAssets();
InputStream input = null;
try {
input = manager.open("test.txt");
} catch (IOException e1) {
Log.d("ERROR DETECTED", "ERROR WHILE TRYING TO OPEN FILE");
}
try {
char current;
while (input.available() > 0) {
current = (char) input.read();
Log.d("caracter", ""+current);
}
} catch (IOException e) {
e.printStackTrace();
}
Thanks for your help guys :)
EDIT: The next code will read all file lines while the above not:
AssetManager manager = getContext().getAssets();
InputStream input = null;
InputStreamReader in = null;
try {
input = manager.open("teste.txt");
in = new InputStreamReader(input);
} catch (IOException e1) {
Log.d("ERROR DETECTED", "ERROR WHILE TRYING TO OPEN FILE");
}
try {
char current;
while (in.ready()) {
current = (char) in.read();
Log.d("caracter", ""+current);
}
} catch (IOException e) {
e.printStackTrace();
}
To read files in character units, often used to read text, Numbers, and other types of files
public static char[] readFileByChars(File file) {
CharArrayWriter charArrayWriter = new CharArrayWriter();
char[] tempBuf = new char[100];
int charRead;
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((charRead = bufferedReader.read(tempBuf)) != -1) {
charArrayWriter.write(tempBuf, 0, charRead);
}
bufferedReader.close();
return charArrayWriter.toCharArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

read text file from phone memory in android

I just wanna create a text file into phone memory and have to read its content to display.Now i created a text file.But its not present in the path data/data/package-name/file name.txt & it didn't display the content on emulator.
My code is..
public class PhonememAct extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=(TextView)findViewById(R.id.tv);
FileOutputStream fos = null;
try {
fos = openFileOutput("Test.txt", Context.MODE_PRIVATE);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fos.write("Hai..".getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = openFileInput("Test.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int c;
try {
while((c=fis.read())!=-1)
{
tv.setText(c);
setContentView(tv);
//k += (char)c;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks in adv.
You don't need to use input/output streams if you are simply trying to write/read text.
Use FileWriter to write text to a file and BufferedReader to read text from a file - it's much simpler. This works perfectly...
try {
File myDir = new File(getFilesDir().getAbsolutePath());
String s = "";
FileWriter fw = new FileWriter(myDir + "/Test.txt");
fw.write("Hello World");
fw.close();
BufferedReader br = new BufferedReader(new FileReader(myDir + "/Test.txt"));
s = br.readLine();
// Set TextView text here using tv.setText(s);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from 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');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
//To read file from internal phone memory
//get your application context:
Context context = getApplicationContext();
filePath = context.getFilesDir().getAbsolutePath();
File file = new File(filePath, fileName);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
return text.toString(); //the output text from file.
This may not be an answer to your question.
I think, you need to use the try-catch correctly.
Imagine openFileInput() call fails, and next you are calling fos.write() and fos.close() on a null object.
Same thing is seen later in fis.read() and fis.close().
You need to include openFileInput(), fos.write() and fos.close() in one single try-catch block. Similar change is required for 'fis' as well.
Try this first!
You could try it with a stream.
public static void persistAll(Context ctx, List<myObject> myObjects) {
// save data to file
FileOutputStream out = null;
try {
out = ctx.openFileOutput("file.obj",
Context.MODE_PRIVATE);
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(myObjects);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is working fine for me like this. Saving as text shouldn't be that different, but I don't have a Java IDE to test here at work.
Hope this helps!

Categories

Resources