public boolean isValid(String username, String password) {
boolean valid = false;
DataInputStream file = null;
try{
Scanner files = new Scanner(new BufferedReader(new FileReader("files/students.txt")));
while(files.hasNext()){
System.out.println(files.next());
}
}catch(Exception e){
e.printStackTrace();
}
return valid;
}
How come when I am reading a file that has been written by UTF-8(By another java program) it displays with weird symbols followed by its String name?
I wrote it using this
private static void addAccount(String username,String password){
File file = new File(file_name);
try{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file,true));
dos.writeUTF((username+"::"+password+"\n"));
}catch(Exception e){
}
}
When using
DataOutput.writeUTF
/DataInput.readUTF
, the first 2 bytes form an unsigned 16-bit big-endian integer denoting the size of the string.These are likely the cause for your issues. You'd need to skip the first 2 bytes and then specify your
Scanner
use UTF-8 to read properly.That being said, I do not see any reason to use
DataOutput
/DataInput
here. You can merely useFileReader
andFileWriter
instead. These will use the default system encoding.From the
FileReader
Javadoc:So perhaps something like
new InputStreamReader(new FileInputStream(file), "UTF-8"))
Here is a simple way to do that: