How to use escape chars when reading a file? - java

I have a method that reads a random joke from a file in raw, and then displays it, but i can't figure out, how to set a new line.
All the jokes in the line are 1 line, but obviously they are more than one so i use \n. For instance the line says "Hi! \n Hi to you too" When i use my code instead of:
Hi!
Hi to you too
it gives me
Hi! \n Hi to you too
I tried to append it, and that didn't work with the code bellow also tried to enter the joke in array and then display it from that array, did't work either... Any ideas would be much appreciated...
InputStreamReader inputStream = new InputStreamReader
(getResources().openRawResource(R.raw.vicove));
BufferedReader br = new BufferedReader(inputStream);
int numLines = 1;
Random r = new Random();
int desiredLine = r.nextInt(numLines);
String theLine="";
int lineCtr = 0;
try {
while ((theLine = br.readLine()) != null) {
if (lineCtr == desiredLine) {
break;
}
lineCtr++;
}
} catch (IOException e) {
e.printStackTrace();
}
textGenerateNumber.setText(String.valueOf(theLine));
I've used the same code to read files with no escape characters and it works perfectly...
P.S. Not only \n wouldn't work, but also \" and probably any other.

try this:
String source = "<br>"+String.valueOf(theLine);
textGenerateNumber.append(Html.fromHtml(source));

It's because you have
\n
in the file, and that are 2 normal characters, not a newline.
You can use Apache Commons library to unescape these sequences:
StringEscapeUtils.unescapeJava in Apache Commons.

Related

What am I missing? NumberFormatException error

I want to read from a txt file which contains just numbers. Such file is in UTF-8, and the numbers are separated only by new lines (no spaces or any other things) just that. Whenever i call Integer.valueOf(myString), i get the exception.
This exception is really strange, because if i create a predefined string, such as "56\n", and use .trim(), it works perfectly. But in my code, not only that is not the case, but the exception texts says that what it couldn't convert was "54856". I have tried to introduce a new line there, and then the error text says it couldn't convert "54856
"
With that out of the question, what am I missing?
File ficheroEntrada = new File("C:\\in.txt");
FileReader entrada =new FileReader(ficheroEntrada);
BufferedReader input = new BufferedReader(entrada);
String s = input.readLine();
System.out.println(s);
Integer in;
in = Integer.valueOf(s.trim());
System.out.println(in);
The exception text reads as follows:
Exception in thread "main" java.lang.NumberFormatException: For input string: "54856"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.valueOf(Integer.java:989)
at Quicksort.main(Quicksort.java:170)
The file in.txt consists of:
54856
896
54
53
2
5634
Well, aparently it had to do with Windows and those \r that it uses... I just tried executing it on a Linux VM and it worked. Thanks to everyone that answered!!
Try reading the file with Scanner class has use it's hasNextInt() method to identify what you are reading is Integer or not. This will help you find out what String/character is causing the issue
public static void main(String[] args) throws Exception {
File ficheroEntrada = new File(
"C:\\in.txt");
Scanner scan = new Scanner(ficheroEntrada);
while (scan.hasNext()) {
if (scan.hasNextInt()) {
System.out.println("found integer" + scan.nextInt());
} else {
System.out.println("not integer" + scan.next());
}
}
}
If you want to ensure parsability of a string, you could use a Pattern and Regex that.
Pattern intPattern = Pattern.compile("\\-?\\d+");
Matcher matcher = intPattern.matcher(input);
if (matcher.find()) {
int value = Integer.parseInt(matcher.group(0));
// ... do something with the result.
} else {
// ... handle unparsable line.
}
This pattern allows any numbers and optionally a minus before (without whitespace). It should definetly parse, unless it is too long. I don't know how it handles that, but your example seems to contain mostly short integers, so this should not matter.
Most probably you have a leading/trailing whitespaces in your input, something like:
String s = " 5436";
System.out.println(s);
Integer in;
in = Integer.valueOf(s.trim());
System.out.println(in);
Use trim() on string to get rid of it.
UPDATE 2:
If your file contains something like:
54856\n
896
54\n
53
2\n
5634
then use following code for it:
....your code
FileReader enter = new FileReader(file);
BufferedReader input = new BufferedReader(enter);
String currentLine;
while ((currentLine = input.readLine()) != null) {
Integer in;
//get rid of non-numbers
in = Integer.valueOf(currentLine.replaceAll("\\D+",""));
System.out.println(in);
...your code

Scanner difficulties with different escape characters

First off let me start by saying that I know I'm not the only one who has experienced this issue and I spent the last couple of hours to research how to fix it. Sadly, I can't get my scanner to work. I'm new to java so I don't understand more complicated explanations that some answers have in different questions.
Here is a rundown:
I'm trying to read out of a file which contains escape characters of cards. Here is a short version: (Numbers 2 and 3 of 4 different card faces)
\u26602,2
\u26652,2
\u26662,2
\u26632,2
\u26603,3
\u26653,3
\u26663,3
\u26633,3
This is the format: (suit)(face),(value). an example:
\u2663 = suit
3 = face
3 = value
This is the code I'm using for reading it:
File file = new File("Cards.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] temp = line.split(",");
cards.add(new Card(temp[0], Integer.parseInt(temp[1])));
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
the ArrayList cards should have 52 cards after this containing a name (suit and face) and a value. When i try to print the name this is the output:
\u26633
While it should be:
♣3
Can anyone give me pointers towards a solution? I really need this issue resolved. I don't want you to write my code for me.
Thanks in advance
Simply store directly the suit characters into your files Cards.txt using UTF-8 as character encoding instead of the corresponding unicode character format that is only understood by java such that when it is read from your file it is read as the String "\u2660" not as the corresponding unicode character.
Its content would then be something like:
♠2,2
...
Another way could be to use StringEscapeUtils.unescapeJava(String input) to unescape your unicode character.
The code change would then be:
cards.add(new Card(StringEscapeUtils.unescapeJava(temp[0]), Integer.parseInt(temp[1])));
You'll have to save your file with UTF-8 encoding and then read the file using the same encoding.
♥,1
♥,2
♥,3
Here is the code snippet:
BufferedReader buff = new BufferedReader(new InputStreamReader(
new FileInputStream("Cards.txt"), "UTF-8"));
String input = null;
while (null != (input = buff.readLine())) {
System.out.println(input);
String[] temp = input.split(",");
cards.add(new Card(temp[0], Integer.parseInt(temp[1])));
}
buff.close();
Also, you need to make sure that your console is enabled to support UTF-8. Look at this answer to read more about it.

Scanner and Buffered reader not showing double quotation marks Java Android

I'm trying to load from a .txt file. Like most .txt files, it's UTF-8 encoded, so it shows double-quotation mark characters when I load it inside of eclipse.
The problem is, when I load my text file into bufferedreader (also set to UTF-8 encoding), it converts double quotation marks and a few other characters into question mark boxes on my device.
I can't figure out what could be the problem, searches here and on Google are all talking about Arabic characters. Please help.
edit: ... updating question... one minute
edit2: I'm displaying them inside a TextView.
The following is from a method. Scanner wasn't working either so I used this:
InputStream in;
in = getResources().openRawResource(R.id.text);
BufferedReader br = new BufferedReader(new InputStreamReader(in,Charset.forName("UTF-8")));
ArrayList<String> letters = new ArrayList<String>(25);
try {
String line="";
while((line = br.readLine()) != null){
String[] splited = line.split("\\s+");
int m = 0;
String word="";
while(m<splited.length){
m++; // analyze the word and do some other stuff here
letters.add(word);
}
}
in.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
Here is where I display my text inside a handler:
final Textview txt = (TextView) rootView.findViewById(R.id.something);
// handler stuff, then inside the handler:
txt.setText(word, BufferType.SPANNABLE);
Spannable s = (Spannable)txt.getText();
s.setSpan(new ForegroundColorSpan(0xFFFFFFFF),2,3,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
I removed the spannable, no dice.
To see what you default notepad saves your txt files as, just go to file>>save as, then along the bottom or in some kind of options menu there should be something about character encoding

BufferedReader gives missing characters

So I am trying to change the format of a text file that has line numbers every couple of lines just to make it cleaner and easier to read. I made a simple program that goes in and replaces all of the first three characters of a line with spaces, these three character spaces are where the numbers can be. The actual text doesn't start until a few more spaces in. When i do this and have the end result printed out it comes out with a diamond with a question mark in it and I'm assuming that this is the result of missing characters. It seems like most of the missing characters are the apostrophe symbol. If anyone could let me know how to fix it i would really appreciate it :)
public class Conversion {
public static void main(String args[]) throws IOException {
BufferedReader scan = null;
try {
scan = new BufferedReader(new FileReader(new File("C:\\Users\\Nasir\\Desktop\\Beowulftesting.txt")));
} catch (FileNotFoundException e) {
System.out.println("failed to read file");
}
String finalVersion = "";
String currLine;
while( (currLine = scan.readLine()) !=null){
if(currLine.length()>3)
currLine = " "+ currLine.substring(3);
finalVersion+=currLine+"\n";
}
scan.close();
System.out.println(finalVersion);
}
}
Instead of using FileReader, use an InputStreamReader with the correct text encoding. I think the strange characters are appearing because you're reading the file with the wrong encoding.
By the way, don't use += with strings in a loop, like you have. Instead, use a StringBuilder:
StringBuilder finalVersion = new StringBuilder();
String currLine;
while ((currLine = scan.readLine()) != null) {
if (currLine.length() > 3) {
finalVersion.append(" ").append(currLine.substring(3));
} else {
finalVersion.append(currLine);
}
finalVersion.append('\n');
}

Reading Integer values from a file (Java)

I'm working on a simple level editor for my Android game. I've written the GUI (which draws a grid) using swing. You click on the squares where you want to position a tile and it changes colour. Once you're done, you write everything to a file.
My file consists of something like the following (this is just an example):
I use the asterisks to determine the level number being read and the hyphen to tell the reader to stop reading.
My file reading code is below, Selecting which part to read works OK - for example. if I pass in 2 by doing the following:
readFile(2);
Then it prints all of the characters in the 2nd section
What I can't figure out is, once I've got to the 'start' point, how do I actually read the numbers as integers and not individual characters?
Code
public void readFile(int level){
try {
//What ever the file path is.
File levelFile = new File("C:/Temp/levels.txt");
FileInputStream fis = new FileInputStream(levelFile);
InputStreamReader isr = new InputStreamReader(fis);
Reader r = new BufferedReader(isr);
int charTest;
//Position the reader to the relevant level (Levels are separated by asterisks)
for (int x =0;x<level;x++){
//Get to the relevant asterisk
while ((charTest = fis.read()) != 42){
}
}
//Now we are at the correct read position, keep reading until we hit a '-' char
//Which indicates 'end of level information'
while ((charTest = fis.read()) != 45){
System.out.print((char)charTest);
}
//All done - so close the file
r.close();
} catch (IOException e) {
System.err.println("Problem reading the file levels.txt");
}
}
Scanner's a good answer. To remain closer to what you have, use the BufferedReader to read whole lines (instead of reading one character at a time) and Integer.parseInt to convert from String to Integer:
// get to starting position
BufferedReader r = new BufferedReader(isr);
...
String line = null;
while (!(line = reader.readLine()).equals("-"))
{
int number = Integer.parseInt(line);
}
If you use the BufferedReader and not the Reader interface, you can call r.readLine(). Then you can simply use Integer.valueOf(String) or Integer.parseInt(String).
Perhaps you should consider using readLine which gets all the chars up the the end of line.
This part:
for (int x =0;x<level;x++){
//Get to the relevant asterisk
while ((charTest = fis.read()) != 42){
}
}
Can change to this:
for (int x =0;x<level;x++){
//Get to the relevant asterisk
while ((strTest = fis.readLine()) != null) {
if (strTest.startsWith('*')) {
break;
}
}
}
Then, to read the values another loop:
for (;;) {
strTest = fls.readLine();
if (strTest != null && !strTest.startsWith('-')) {
int value = Integer.parseInt(strTest);
// ... you have to store it somewhere
} else {
break;
}
}
You also need some code in there to handle errors including a premature end of file.
I think you should have look at the Scanner API in Java.
You can have a look at their tutorial

Categories