I am using the code below to read the the txt files from my SD card, but how can I display it as Text View?
try{
File f = new File(Environment.getExternalStorageDirectory()+"/filename.txt");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
This should do it :
public void displayOutput()
{
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"/TextFile.txt");
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) {
Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),"File not found!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
TextView output=(TextView) findViewById(R.id.output);
// Assuming that 'output' is the id of your TextView
output.setText(text);
}
LinearLayout myVerticalLinearLayout = (LinearLayout) findViewById(R.id.myLinearLayout);
TextView text = new TextView(getApplicationContext());
text.setText(readString);
myVerticalLinearLayout.addView(text);
That should add vertical text views in a linear layout you should have created before.
public String readText(){
//this is your text
StringBuilder text = new StringBuilder();
try{
File f = new File(Environment.getExternalStorageDirectory()+"/filename.txt");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = "";
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
text.append(readString + "\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return text.toString();
}
...
TextView tv=findViewById(.....);
tv.setText(readText());
public class ReadFileActivity extends Activity {
/** Called when the activity is first created. */
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text=(TextView)findViewById(R.id.textview);
text.setText(readTxt());
}
private String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.aaa);
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();
}
return byteArrayOutputStream.toString();
}
}
Related
I got button wich save changes, and put this in internal storage, then when app start I want to read file if there is any ofc. i thought that would be enought but im fresh coder and dunno that is good.
I dont know where is mistake, and also that is good code, pls help me becous i stuck
My code:
public class MyGameDetailsFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_game_details, container, false);
try {
FileInputStream is = getActivity().openFileInput(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
} catch(OutOfMemoryError om) {
om.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
String result = sb.toString();
saveBtn = (Button) view.findViewById(R.id.savechangesbtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Data1 = s1.getText().toString();
Data2 = s2.getText().toString();
Data3 = s3.getText().toString();
Data4 = s4.getText().toString();
Data5 = s5.getText().toString();
Data6 = s6.getText().toString();
try {
FileOutputStream fos=getActivity().openFileOutput(file, getActivity().MODE_PRIVATE);
ObjectOutputStream outputStream = new ObjectOutputStream(fos);
outputStream.write(Data1.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data2.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data3.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data4.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data5.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data6.getBytes());
outputStream.close();
//Toast.makeText(context,"file saved",Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream inputStream = getActivity().openFileInput(file);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
}
});
return view;
}
}
Ps: s1,s2 etc are created in code etc
Permission
<uses-permission android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Other = (TextView) view.findViewById(R.id.Details);
OtherD = (TextView) view.findViewById(R.id.OtherDetails);
try {
FileInputStream is = getActivity().openFileInput(file);
byte[] input = new byte[is.available()];
while(is.read(input) != -1){
value += new String(input);
}
is.getFD().sync();
//is.flush();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] strArray = value.split(";");
s1.setText(strArray[1]);
s2.setText(strArray[2]);
s3.setText(strArray[3]);
s4.setText(strArray[4]);
s5.setText(strArray[5]);
s6.setText(strArray[6]);
s7.setText(strArray[7]);
saveBtn = (Button) view.findViewById(R.id.savechangesbtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Data1 = s1.getText().toString();
Data2 = s2.getText().toString();
Data3 = s3.getText().toString();
Data4 = s4.getText().toString();
Data5 = s5.getText().toString();
Data6 = s6.getText().toString();
Data7= s7.getText().toString();
try {
FileOutputStream fos=getActivity().openFileOutput(file, getActivity().MODE_PRIVATE);
ObjectOutputStream outputStream = new ObjectOutputStream(fos);
outputStream.write(string3.getBytes());
outputStream.write(Data1.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data2.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data3.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data4.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data5.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data6.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data7.getBytes());
outputStream.write(string3.getBytes());
//outputStream.getFD().sync();
outputStream.flush();
outputStream.close();
//Toast.makeText(context,"file saved",Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream inputStream = getActivity().openFileInput(file);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Solve it on my own
First of all i would suggest you that, Dont write code in OnCreateView() method in fragments, always write code in OnViewCreated method.
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_game_details, container, false);
return view;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
try {
FileInputStream is = getActivity().openFileInput(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
} catch(OutOfMemoryError om) {
om.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
String result = sb.toString();
saveBtn = (Button) view.findViewById(R.id.savechangesbtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Data1 = s1.getText().toString();
Data2 = s2.getText().toString();
Data3 = s3.getText().toString();
Data4 = s4.getText().toString();
Data5 = s5.getText().toString();
Data6 = s6.getText().toString();
try {
FileOutputStream fos=getActivity().openFileOutput(file, getActivity().MODE_PRIVATE);
ObjectOutputStream outputStream = new ObjectOutputStream(fos);
outputStream.write(Data1.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data2.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data3.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data4.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data5.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data6.getBytes());
outputStream.close();
//Toast.makeText(context,"file saved",Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream inputStream = getActivity().openFileInput(file);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
If you are facing any error, then Please write the stacktrace of error.
Thanks
Cheers!! Simplicity is the best!
I have been working on this for a while and I am about to pull my hair out!!
If I use this...
public void readFile() {
BufferedReader buffReader = null;
StringBuilder result = new StringBuilder();
try {
FileInputStream fileIn = openFileInput("VariableStore.txt");
buffReader = new BufferedReader(new InputStreamReader(fileIn));
String line;
while ((line = buffReader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert buffReader != null;
buffReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String resultString = result.toString();
String[] controlString = resultString.split("$");
// String wb = controlString[4];
// String sb = controlString[5];
((Button) this.findViewById(R.id.wakeButton)).setText(resultString);
// ((Button) this.findViewById(R.id.sleepButton)).setText(sb);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
}
The Button.setText works fine with "resultString" or with "result" which is a string I have input formatted as xxx$xxx$xxx$xxx$xxx so when I read it back in with the readFile() I want to use .Split and put it into an array "controlString" and then assign the array elements to my widgets i.e. setText(controlString[0]); but if I so much as even uncomment the lines String wb = controlString[4]; or String sb = controlString[5]; my program crashes. Why wont the array elemts work here?
Here is my writeFile().... (Which works perfectly.
public void writeFile() {
BufferedWriter buffWriter = null;
String wb = ((Button)this.findViewById(R.id.wakeButton)).getText().toString();
String sb = ((Button)this.findViewById(R.id.sleepButton)).getText().toString();
String tb = ((EditText)this.findViewById(R.id.textHoursBetween)).getText().toString();
String ti = ((EditText)this.findViewById(R.id.textIncrementTime)).getText().toString();
String td = ((EditText)this.findViewById(R.id.textIncrementDays)).getText().toString();
String writeString = wb + "$" + sb + "$" + tb + "$" + ti + "$" + td;
try {
FileOutputStream fileOut = openFileOutput("VariableStore.txt", Context.MODE_PRIVATE);
buffWriter = new BufferedWriter(new OutputStreamWriter(fileOut));
try {
buffWriter.write(writeString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
assert buffWriter != null;
buffWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found the problem...
Instead of this:
String[] controlString = resultString.split("$");
I had to use this:
String[] controlString = resultString.split(Pattern.quote("$"));
I have succesfully saved int values to sd but cant read. It always gives numberformat information. I made all logics, but cant find why it gives error.
Here is my code ;
this my constant
private final static String EXTERNAL_FILES_DIR = "ARDROID";
private final static String FILE_NAME = "turkcell.txt";
private boolean isThereAnySavedFile = false;
when this method called, it tries to open file, if file does not exist, create the file
public void anySavedDataInSD() {
String textFromSD = String.valueOf(read());
if (isThereAnySavedFile) {
int numberOfSendedSMS = Integer.parseInt(textFromSD.toString());
numberOfSendedSMS++;
writeToSD(String.valueOf(numberOfSendedSMS));
} else {
int first=60;
String g = String.valueOf(first);
writeToSD(g);
}
}
this method for writing
private void write(File file, String msg) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(msg.getBytes());
Logger.info("oldu bu kez");
} catch (IOException e) {
Logger.info("oldu bu kez2" + e);
} finally {
Logger.info("oldu bu kez3");
try {
if (outputStream != null)
outputStream.close();
} catch (IOException exception) {
}
}
}
this methof for reading
public StringBuilder read() {
StringBuilder textBuilder = new StringBuilder();
BufferedReader reader = null;
try {
File externalFilesDir = getExternalFilesDir(EXTERNAL_FILES_DIR);
File file = new File(externalFilesDir, FILE_NAME);
Logger.info("oldu2");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
isThereAnySavedFile = true;
} catch (FileNotFoundException e) {
Logger.info("oldu3");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return textBuilder;
}
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();
}
}
I am trying to make the computer read a text file full of words and add it to an ArrayList. I made it work on a regular Java application, but can't get it to work on Android. Can someone help me out?
try {
FileInputStream textfl = (FileInputStream) getAssets().open("test.txt");
DataInputStream is = new DataInputStream(textfl);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String strLine;
while ((strLine = r.readLine()) != null) {
tots.add(strLine); //tots is the array list
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I keep getting a error. The text file is 587kb, so could that be a problem?
try this.
private static String readTextFile(String fileName)
{
BufferedReader in = null;
try
{
in = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
String line;
final StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
{
buffer.append(line).append(System.getProperty("line.separator"));
}
return buffer.toString();
}
catch (final IOException e)
{
return "";
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
// ignore //
}
}
}