I have created a txt file and saved it in the file Explorer at data/data/com.xxx/files/mynote/txt when I entered a string into edit text and click the button.
I want compare txt file content and input String. In my txt file, only minimum length 5 to 6 is stored. How do I do this? I have tried but it can not compare properly - it goes to else block part when I entered the same string as i save in my txt file like "tazin".
Here is my code.
btnSubmitCode=(Button)findViewById(R.id.button_Submit);
btnSubmitCode.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(editText_Code.getText().toString().isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Enter Code", Toast.LENGTH_SHORT).show();
}
else
{
String strCode = editText_Code.getText().toString().trim();
create_File(strCode);
readFile();
}
String temp;
String searchString = "tazin";
try {
File file=new File("/data/data/com.xxxxx/files/mynote.txt/");
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.readLine() != null)
{
temp = in.readLine();
System.out.println("String from txt file ="+temp);
if(searchString.equals(temp))
{
System.out.println("word is match");
in.close();
return;
}
else
{
System.out.println("word is not match");
}
}
in.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//Write File
private void create_File(String strtext)
{
FileOutputStream fos = null;
try
{
fos = openFileOutput("mynote.txt", MODE_PRIVATE);
fos.write(strtext.getBytes());
Toast.makeText(getApplicationContext(), "File created succesfully",
Toast.LENGTH_SHORT).show();
}
catch(FileNotFoundException fexception)
{
fexception.printStackTrace();
}
catch(IOException ioexception)
{
ioexception.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
// drain the stream
fos.flush();
fos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//Read File
private void readFile()
{
FileInputStream fis;
try
{
fis = openFileInput("mynote.txt");
byte[] reader = new byte[fis.available()];
while (fis.read(reader) != -1)
{
}
textView_ReadCode.setText(new String(reader));
strReadFile = new String(reader);
System.out.println("Read File Into String Format " + strReadFile);
Toast.makeText(getApplicationContext(), "File read succesfully",
Toast.LENGTH_SHORT).show();
if (fis != null)
{
fis.close();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
Log.e("Read File", e.getLocalizedMessage());
}
}
You're misusing the BufferedReader.readLine() method. You're calling it twice each time through your while loop; once in the while conditional, and once in the loop block itself. So, when you do temp = in.readLine() and then the searchString.equals(temp) comparison, you've already skipped a line from the text file. Structure your loop like so:
temp = in.readLine();
while (temp != null)
{
System.out.println("String from txt file =" + temp);
if(searchString.equals(temp))
{
System.out.println("word is match");
in.close();
return;
}
else
{
System.out.println("word is not match");
}
temp = in.readLine();
}
Edit:
Per our chat in comments, here is the updated code for what you need:
btnSubmitCode.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
String str = editText_Code.getText().toString();
if(str == null || str.equals(""))
{
Toast.makeText(getApplicationContext(), "Please Enter Code", Toast.LENGTH_SHORT).show();
}
else
{
String strCode = str.trim();
if(checkCode(strCode))
{
System.out.println("word is match");
}
else
{
System.out.println("word is not match");
}
}
}
}
);
...
...
// Returns true if the code has already been used
// Returns false if the code is new
// Creates mynote.txt if it doesn't exist
// Appends code if it is new
private boolean checkCode(String code)
{
String temp;
File file = new File(getFilesDir() + "mynote.txt");
if(file.exists())
{
try
{
BufferedReader in = new BufferedReader(new FileReader(file));
temp = in.readLine();
while (temp != null)
{
if(code.equals(temp))
{
// Match was found
// Clean up and return true
in.close();
return true;
}
temp = in.readLine();
}
in.close();
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
}
}
// Match was not found or File doesn't exist
// Append code to mynote.txt and return false
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
out.newLine();
out.write(code);
out.close();
}
catch (IOException e)
{
}
return false;
}
In your question you wrote different path then you write in your code so just check your path of file.
Related
I want to login from a text file called "members.txt" which using 2nd (username) and third (password) line with "/" delimiter. But when I run it, it seems they recognize all of text file's account in sequence. Please help. Here's my code.
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String s;
String bypassid = "guest";
String bypasspw = "guest";
String[] array;
boolean isLogin= false; // 포기
BufferedReader br = new BufferedReader(new FileReader("members.txt"));;
while((s=br.readLine())!=null) {
array=s.split("/");
if(txtID.getText().equals(array[1])&&txtPass.getText().equals(array[2])){
JOptionPane.showMessageDialog(null, "로그인 되셨습니다");
break;
} else if(array.length != 0 && bypassid.equals(txtID.getText())&&bypasspw.equals(txtPass.getText())){
JOptionPane.showMessageDialog(null, "로그인 되셨습니다");
break;
} else {
JOptionPane.showMessageDialog(null, "계정 정보를 다시 확인해주세요.");
}
}
br.close();
} catch (IOException e10) {
// TODO Auto-generated catch block
e10.printStackTrace();
}
}
});
Actually you are reading every line and if user/password doesn't match, you print error message in else {} block. You can just set boolean variable isLogin once and see if isLogin is false, print error message once outside loop. Below is the code snippet for that. Replace your actionPerformed method with code below
public void actionPerformed(ActionEvent e) {
try {
String s;
String bypassid = "guest";
String bypasspw = "guest";
String[] array;
boolean isLogin= false; // 포기
BufferedReader br = new BufferedReader(new FileReader("members.txt"));
while((s=br.readLine())!=null) {
array=s.split("/");
if(txtID.getText().equals(array[1])&&txtPass.getText().equals(array[2])){
JOptionPane.showMessageDialog(null, "로그인 되셨습니다");
isLogin = true;
break;
} else if(array.length != 0 && bypassid.equals(txtID.getText())&&bypasspw.equals(txtPass.getText())){
JOptionPane.showMessageDialog(null, "로그인 되셨습니다");
isLogin = true;
break;
}
}
if(!isLogin) {
JOptionPane.showMessageDialog(null, "계정 정보를 다시 확인해주세요.");
}
br.close();
} catch (IOException e10) {
// TODO Auto-generated catch block
e10.printStackTrace();
}
}
Just be careful about what #David Kroukamp mentioned in comment
My project is list of music that user can set as ringtone.
All of my music is located in raw and it works correctly and also my ringtone name is a text in raw "zeallist".
My problem is that how to put my music in asset folder.
Here is my code that play music from raw:
public ArrayList<SongInfo> getAllSong(Context context) {
ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
RingtonesSharedPreferences pref = new RingtonesSharedPreferences(
context);
Field[] fields = R.raw.class.getFields();
for (int i = 0; i < fields.length - 1; i++) {
SongInfo info = new SongInfo();
try {
String name = fields[i].getName();
if (!name.equals("ringtones")) {
info.setFileName(name + ".mp3");
info.setFavorite(pref.getString(info.getFileName()));
int audioResource = R.raw.class.getField(name).getInt(name);
info.setAudioResource(audioResource);
}
// info.setName(name);
} catch (Exception e) {
}
listSong.add(info);
}
InputStream inputStream = context.getResources().openRawResource(
R.raw.zeallist);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
try {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
listSong.get(i).setName(line);
i++;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listSong;
}
How to change this part of my code to read them from asset and return my listsong ?
Core part I have finished.Some details you need do yourself
public ArrayList<SongInfo> getAllSong(Context context) throws IOException {
ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
RingtonesSharedPreferences pref = new RingtonesSharedPreferences(context);
String[] files = context.getAssets().list("Your songs path");
for (int i = 0; i < files.length - 1; i++) {
SongInfo info = new SongInfo();
String name = files[i];
if (!name.equals("ringtones")) {
info.setFileName(name + ".mp3");
info.setFavorite(pref.getString(info.getFileName()));
/* int audioResource = R.raw.class.getField(name).getInt(name);
info.setAudioResource(audioResource);*/ //fileName is enough to you
}
// info.setName(name);
listSong.add(info);
}
InputStream inputStream = context.getAssets().open("Your zeallist path");
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
try {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
listSong.get(i).setName(line);
i++;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listSong;
}
When you want to play corresponding music, you could do like this
public void play(MediaPlayer mediaPlayer, Context context, String musicName) throws IOException {
AssetFileDescriptor assetFileDescriptor = context.getAssets().openFd(musicName);
mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength());
mediaPlayer.prepare();
mediaPlayer.start();
}
Hope this will solve your problem .
Right click on res folder and Create new folder called raw. Now copy paste few .MP3 files inside it. Check those links for better understanding.
link1
link2
From Assest folder
public void playBeep() {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("mysong.mp3");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
mp.setVolume(1f, 1f);
mp.setLooping(true);
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
You can read file from asset using AssetManager
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");
Note that this file is String array. So don't forget to initialize new file for each element of the array before iterating over it.
I've looked through the other threads on here and can't find anything that works for me. What I need to do is read a text file from the external storage and copy the text to a string in my Java file. After it gets converted I need it to compare that string to one typed in by the user in an Edittext. This is what I have so far and I'm sure there's a lot wrong with it.
try {
decrypt();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
final EditText pin = (EditText) findViewById(R.id.pin);
pin.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
File file = new File(Environment.getExternalStorageDirectory().toString() + "/Vault/data1.txt");
String pinkey = pin.getText().toString();
if (pinkey.matches("")) {
Toast.makeText(MainActivity.this, "Type in pin", Toast.LENGTH_LONG).show();
}
else {
try {
decrypt();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
StringBuilder text = new StringBuilder();
String key = new String(file.toString());
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
if (file.exists()) {
} else {
showHelp(null);
}
if (pinkey.equals(br)) {
Toast.makeText(MainActivity.this, "You're signed in", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Try again", Toast.LENGTH_LONG).show();
}
}
return true;
}
return false;
}
Any help is appreciated!
Silly me. I should probably use the scroll bar before commenting :p
Anyways, try your try block like this
BufferedReader br = new BufferedReader(new FileReader(file));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String fileAsString = sb.toString();
} finally {
br.close();
}
Not sure if you need a new line separator, but if your comparing it to another file it might be good to get it in a form that represents a file...I'd assume.
You can use a simple Scanner and File objects:
public String readFile(String path) {
try {
Scanner se = new Scanner(new File(path));
String txt = "";
while (se.hasNext())
txt += se.nextLine() + "\n";
se.close();
return txt;
} catch (FileNotFoundException e) {
return null;
}
}
You open a scanner that scans the file, and as long as there is more to read from the file, you append the next line to a string.
This method returns null if the file doesn't exist, and an empty string if the file is empty.
I am trying to save an int (score) on the Internal storage of a real device, and for some reason, when I load it, it makes score equals to 0.
Code:
public int score;
String scoreString = Integer.toString(score);
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
final TextView best = (TextView) findViewById(R.id.best);
// Save
try {
file = getFilesDir();
fileOutputStream = openFileOutput("record.txt", Context.MODE_PRIVATE);
fileOutputStream.write(scoreString.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(MainActivity.this, "Save() works fine " + scoreString + file, Toast.LENGTH_SHORT).show();
// load
try {
FileInputStream fileInputStream = openFileInput("record.txt");
int read = -1;
StringBuffer buffer = new StringBuffer();
while ((read = fileInputStream.read()) != -1){
buffer.append((char)read);
}
Log.i("ELY", buffer.toString());
String record = buffer.substring(0);
best.setText("Best: " + record);
Toast.makeText(MainActivity.this, "Load() OK " + record , Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can somebody help me? Thanks
UPDATED Well If you just want to save score you can use SharedPrefernces
To get Score:
public int getScore() {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MY_PREFS", context.MODE_PRIVATE);
return pref.getInt("SCORE", 0);
}
To store Score:
public void setScore(int score) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MY_PREFS", context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("SCORE", score);
editor.commit();
}
I have a file stored locally on my device that I read from perfectly fine if I don't reboot the phone. When I reboot and read the logs, new FileReader throws an NPE; why?
BufferedReader br = null;
FileReader fr = null;
try {
Log.d("DEBUG", "Before filereader");
fr = new FileReader(ABS_FILENAME);
Log.d("DEBUG", "Before BufferedReader");
br = new BufferedReader(fr);
String current;
Log.d("DEBUG", "About to read file");
while((current = br.readLine()) != null) {
}
}
} catch (Exception e) {
Log.d("DEBUG", "Exception thrown: " + e.getMessage());
} finally {
try {
if (fr != null) {
fr.close();
}
} catch (IOException ex) {
Log.d("DEBUG", "Problem closing file reader");
}
}
return null;
The above code happens in a broadcast receiver. ABS_FILENAME is a string that denotes a file. That file is written to periodically in an Activity once something is clicked:
// in an onClick that gets invoked
try {
String line = myKey + " " + myValue;
fw.write(line);
fw.write(System.getProperty("line.separator"));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// elsewhere in the activity
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
myFile = new File(getFilesDir(), FILENAME);
try {
if (!myFile.exists()) {
myFile.createNewFile();
}
ABS_FILENAME = myFile.getAbsolutePath();
fw = new FileWriter(myFile.getAbsoluteFile(), true);
} catch(IOException e) {
}
If
new FileReader(ABS_FILENAME)
really produces a NullPointerException, clearly ABS_FILENAME must be null.