Does anyone know how i can set the size of a character array to the size of a file? The length method in the File class returns a long value representing the number of bytes in the file. So this declaration long[] c = new long[file.length()]; would be the right size when reading Unicode characters that are encoded using UTF-8 but reading characters that are represented using multiple bytes wouldn't work.
I whipped up this block of code to do the task but there must be a better way. Any ideas? Thanks.
public static int getFileCharCount(String file) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String lineOnebyOne = null;
String finalText = null;
int numberOfChar = 0;
while ((lineOnebyOne = br.readLine ())!= null){
finalText += lineOnebyOne;
numberOfChar = finalText.length();
br.close();
}
return numberOfChar;
}
I whipped up this block of code to do the task but there must be a better way. Any ideas? Thanks.
public static int getFileCharCount(String file) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String lineOnebyOne = null;
String finalText = null;
int numberOfChar = 0;
while ((lineOnebyOne = br.readLine ())!= null){
finalText += lineOnebyOne;
numberOfChar = finalText.length();
br.close();
}
return numberOfChar;
}