Compare a char using equals - java

If I am scanning from a text
Scanner s= new Scanner("texto.txt");
// I want to compare the next char from the line with a <
// like this:
if(s.nextChar().equals("<")){
.....
I know that s.nextChar() does not exist but there is any similar thing to use in this case?

Your code would something like...
Scanner s= new Scanner("texto.txt");
s.useDelimiter("");
while (s.hasNext()) {
if(s.nextChar()=='<'){
.....
}
Note that after the call of s.nextChar(), the value is actually fetched, so its better to keep the variable, if you would like to use it further, like:
char ch = s.nextChar();

Consider dumping Scanner and using FileReader:
FileReader fileReader = new FileReader("textto.txt");
int charRead
while( (charRead = fileReader.read()) != -1)
{
if(charRead == '<')
{
//do something
}
}

FileReader reader = null;
try {
reader = new FileReader("");
int ch = reader.read() ;
while (ch != -1) {
// check for your char here
}
} catch (FileNotFoundException ex) {
//
} catch (IOException ex) {
//
} finally {
try {
reader.close();
} catch (IOException ex) {
//
}
}

Related

How to solve infinite readLine while

I have a program and one of the methods I use is for counting the lines a .txt file has and return an integer value. The problem is when I execute it, despite I wrote if my line is == null the while has to stop, the while loop keeps going, ignoring the nulls it gets infinitely.
I don't know what to do to try to solve it.
private int sizeOfFile (File txt) {
FileReader input = null;
BufferedReader count = null;
int result = 0;
try {
input = new FileReader(txt);
count = new BufferedReader(input);
while(count != null){
String line = count.readLine();
System.out.println(line);
result++;
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
input.close();
count.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
It has to stop when it detects a null, which means there are no more lines, but it keeps going.
When you instantiate a BuffereReader assign it to count, count will always be non-null and hence will satisfy the while loop:
count = new BufferedReader(input); //count is holding an instance of BufferedReader.
while(count != null){ //here count is non-null and while loop is infinite and program never exits.
Instead use the following code, where the each line will be read and checked whether it is null, if null then the program will exit.:
input = new FileReader(txt);
count = new BufferedReader(input);
String line = null;
while(( line = count.readLine())!= null){ //each line is read and assigned to the String line variable.
System.out.println(line);
result++;
}
If you are using JDK-1.8 you can shorten your code using the Files API:
int result = 0;
try (Stream<String> stream = Files.lines(Paths.get(txt.getAbsolutePath()))) {
//either print the lines or take the count.
//stream.forEach(System.out::println);
result = (int)stream.count();
} catch (IOException e) {
e.printStackTrace();
}
count is your BufferedReader, your loop should be on line! Like,
String line = "";
while (line != null) {
line = count.readLine();
Also, you should use try-with-Resources to close your resources (instead of the finally block). And you could write that while loop more idiomatically. Like,
private int sizeOfFile(File txt) {
int result = 0;
try (BufferedReader count = new BufferedReader(new FileReader(txt))) {
String line;
while ((line = count.readLine()) != null) {
System.out.println(line);
result++;
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}

Android InputStream. Read buffer until specific character

I'm handling a Bluetooth connection with Android and I'd like to read the InputStream buffer until I get some specific character like '\n' (new line) or any other character and leave the buffer as it is, then read the following bytes again until the same character is read in order to place them in separate strings. I tried several ways with no success, can anybody help me?
The code I'm using to get the data is the following
public String getData() {
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inStream.read(inString);
}
catch (IOException e){
e.printStackTrace();
}
String str= new String(inString, StandardCharsets.UTF_8);
return str;
}
If you want to read until you find a specific char,
one solution could be something like this:
public static String readUntilChar(InputStream stream, char target) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader buffer=new BufferedReader(new InputStreamReader(stream));
int r;
while ((r = buffer.read()) != -1) {
char c = (char) r;
if (c == target)
break;
sb.append(c);
}
System.out.println(sb.toString());
} catch(IOException e) {
// Error handling
}
return sb.toString();
}
Finally, I got a solution. I don't know if it's the most optimum, but it works fine. I post the code in case it's useful for someone else. Thanks for your responses.
Function to get the input stream char by char:
public char getData() {
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inStream.read(inString,0,1);
}
catch (IOException e){
e.printStackTrace();
}
String str= new String(inString, StandardCharsets.UTF_8);
inChar=str.charAt(0);
return inChar;
}
Function to get the desired strings when the character '&' appears:
public void procesChar(char inChar){
if(inChar=='&'){
String str=new String(charBuffer);
countBytes=0;
Arrays.fill(charBuffer,(char)-1);
}
else {
charBuffer[countBytes] = inChar;
countBytes++;
}
}

How do I skip lines when I'm reading from a text file?

I'm reading from a text file which looks like this:
1
The Adventures of Tom Sawyer
2
Huckleberry Finn
4
The Sword in the Stone
6
Stuart Little
I have to make it so that the user can enter the reference number and the program will perform binary and linear search and output the title. My teacher said to use two ArrayLists, one for the numbers and one for the titles, and output from them. I just can't figure out how to skip lines so I can add to the corresponding arraylist.
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Thanks in advance, I appreciate any help!
You can check if you are in even or odd lines by doing a modulo 2 operation on the line number:
try (BufferedReader br = new BufferedReader(new FileReader("bookList.txt"))) {
String word;
int lineCount = 0;
while ((word = br.readLine()) != null ){
if (++lineCount % 2 == 0) {
numbers.add(Integer.parseInt(word));
} else {
books.add(word);
}
}
} catch (IOException e) {
e.printStackTrace();
}
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
numbers.add(Integer.valueOf(word));
word = br.readLine()
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
You could make check to see if it is actually a integer, that you read from the file. As far as I remember, there is no built in method to do this, but you can define your own as:
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Then just make a check to see if the line you have read in is a integer or not.
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
if (tryParseInt(word))
numbers.add(Integer.parseInt(word))
else
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Hope this help!

Reading every char in a text file

I'm attempting to read in every character (tabs, new lines) in a text file. I'm having some trouble reading all of these in. My current method reads the tabs in but not new lines. Here is the code:
//reads each character in as an integer value returns an arraylist with each value
public static ArrayList<Integer> readFile(String file) {
FileReader fr = null;
ArrayList<Integer> chars = new ArrayList<Integer>(); //to be returned containing all commands in the file
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int tempChar = ' ';
String tempLine = "";
while ((tempLine = br.readLine()) != null) {
for (int i = 0; i < tempLine.length(); i++) {
int tempIntValue = tempLine.charAt(i);
chars.add(tempIntValue);
}
}
fr.close();
br.close();
} catch (FileNotFoundException e) {
System.out.println("Missing file");
System.exit(0);
} catch (IOException e) {
System.out.println("Empty file");
System.exit(0);
}
return chars;
}
I originally used the read() method instead of readLine() but that had the same problem. I'm representing the char as ints. Any help is really appreciated!
I suggest you use try-with-resources, List and the diamond operator <> and that you read each char with the BufferedReader.read() method.
public static List<Integer> readFile(String file) {
List<Integer> chars = new ArrayList<>();
try (FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);) {
int ch;
while ((ch = br.read()) != -1) {
chars.add(ch);
}
} catch (FileNotFoundException e) {
System.out.println("Missing file");
System.exit(0);
} catch (IOException e) {
System.out.println("Empty file");
System.exit(0);
}
return chars;
}
The reason you aren't getting line endings is documented by the BufferedReader.readLine() Javadoc which says in part (emphasis added),
A String containing the contents of the line, not including any line-termination characters...

How to read in information from a file, and store it as a string. Java

ive gotten this far, but this doesnt work to read in the file, thats the part im stuck on. i know that you need to use the scanner, but im not sure what im missing here. i think it needs a path to the file also, but i dont know where to put that in
public class string
{
public static String getInput(Scanner in) throws IOException
{
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter file");
String filename =keyboard.next();
File inputFile = new File(filename);
Scanner input = new Scanner(inputFile);
String line;
while (input.hasNext())
{
line= input.nextLine();
System.out.println(line);
}
input.close();
}
if(filename.isEmpty())
{
System.out.println("Sorry, there has been an error. You must enter a string! (A string is some characters put together.) Try Again Below.");
return getInput(in);
}
else
{
return filename;
}
}
public static int getWordCount(String input)
{
String[] result = input.split(" ");
return result.length;
}
public static void main(String[] args)
{
DecimalFormat formatter = new DecimalFormat("0.##");
String input = getInput(new Scanner(System.in));
float counter = getWordCount(input);
System.out.println("The number of words in this string ("+input+") are: " + counter);
Scanner keyboard= new Scanner(System.in);
}
}
//end of code
First of all, when doing file I/O in Java, you should properly handle all exceptions and errors that can occur.
In general, you need to open streams and resources in a try block, catch all exceptions that happen in a catch block and then close all resources in a finally block. You should read up more on these here as well.
For using a Scanner object, this would look something like:
String token = null;
File file = null;
Scanner in = null;
try {
file = new File("/path/to/file.txt");
in = new Scanner(file);
while(in.hasNext()) {
token = in.next();
// ...
}
} catch (FileNotFoundException e) {
// if File with that pathname doesn't exist
e.printStackTrace();
} finally {
if(in != null) { // pay attention to NullPointerException possibility here
in.close();
}
}
You can also use a BufferedReader to read a file line by line.
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// ...
}
With added exception handling:
String line = null;
FileReader fReader = null;
BufferedReader bReader = null;
try {
fReader = new FileReader("/path/to/file.txt");
bReader = new BufferedReader(fReader);
while ((line = bReader.readLine()) != null) {
// ...
}
} catch (FileNotFoundException e) {
// Missing file for the FileReader
e.printStackTrace();
} catch (IOException e) {
// I/O Exception for the BufferedReader
e.printStackTrace();
} finally {
if(fReader != null) { // pay attention to NullPointerException possibility here
try {
fReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bReader != null) { // pay attention to NullPointerException possibility here
try {
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In general, use the Scanner for parsing a file, and use the BufferedReader for reading the file line by line.
There are other more advanced ways to perform reading/writing operations in Java. Check out some of them here

Categories

Resources