[Q#13370053][A#13370154] How to read an input file char by char using a Scanner?
https://stackoverflow.com/q/13370053
I have to use Scanner, so is there a nextChar() instead of nextLine() method that I could use? Thanks!
Answer
https://stackoverflow.com/a/13370154
You can convert in an array of chars.
APIzation
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("yourFile.txt")));
while (s.hasNext())
{
String str = s.next();
char[] myChar = str.toCharArray();
// do something
}
} finally {
if (s != null) {
s.close();
}
}
}
package com.stackoverflow.api;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.Callable;
public class Human13370154 {
public static void convertToArrayOfCharsAndPrint(String str1)
throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader(str1)));
while (s.hasNext()) {
String str = s.next();
char[] myChar = str.toCharArray();
// do something
}
} finally {
if (s != null) {
s.close();
}
}
}
}
package com.stackoverflow.api;
import java.io.*;
import java.util.Scanner;
/**
* How to read an input file char by char using a Scanner?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/13370154">https://stackoverflow.com/a/13370154</a>
*/
public class APIzator13370154 {
public static void readChar(String str1) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader(str1)));
while (s.hasNext()) {
String str = s.next();
char[] myChar = str.toCharArray();
// do something
}
} finally {
if (s != null) {
s.close();
}
}
}
}