Reading a text file, character by character in java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am currently trying to work with a custom text file to read quests for a small game, however i am having trouble getting the code to read each character, I've done my research and somehow come up with nothing. I am unsure of how to read a .txt file character by character, so if anyone can help or point me in the right direction it would be strongly appreciated.

Path path = Paths.get("filename");
try (Scanner scanner = new Scanner(path, ENCODING.name())){
while (scanner.hasNextLine()){
String s = scanner.nextLine();
for(char c : s.toCharArray()) {
// your code
}
} catch(IOException e) {/* Reading files can sometimes result in IOException */}

If you want to read each character from file you could do something like this:
BufferedReader r=new BufferedReader(new FileReader("file.txt"));
int ch;
while((ch=r.read())!=-1){
// ch is each character in your file.
}
Good luck

File file = new File("text.txt");
Scanner in = new Scanner(file);
// option 1
while(in.hasNext())
{
String temp = in.next();
char[] temparr = temp.toCharArray();
for(Character j: temparr)
{
//do someting....
}
}
// or option 2
in.useDelimiter("");
while(in.hasNext())
{
temp = in.next();
//do something
}
Option 1 gives you the ability to manipulate the string char by char if the condition is true.
Option just reads one char at a time and lets you preform an action but not manipulate the string found in the text file.
public void method() throws FileNotFoundException
if you dont want to use a try catch

Related

Java: 2-dimensional char Array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i've been trying to programm a game called Sokoban the last few days. The levels of the game are simple .txt files you can swap. I've already read the .txt file by using BufferedReader but have problems with saving it to an 2-dimensional char array because the number of rows and columns are different each level. Someone told me to make use of charAt but how do i do that.
Sokobanlevel format (http://www.sokoban-online.de/help/sokoban/level-format.html)
Hope you can help me. Thanks.
String file = "...";
BufferedReader br = Files.newBufferedReader();
String line = null;
int rows = file.length;
int cols = file[0].length;
char[][] room = new char [rows][cols];
while ((line = br.readLine()) != null) {
System.out.println(room[rows][cols]);
}
Without knowlege about the number of lines in the file you need to read everything from the file first to determine the number of lines. This would be easiest, if you use a List<char[]> to store char arrays for each line.
You could easily write something with the same functionality as a one-liner in java 8 though:
File fl = new File(file);
char[][] array = Files.lines(fl.toPath()).map(String::toCharArray).toArray(char[][]::new);
You can initialize 2D arrays so that each row has a different number of columns:
char[][] c = new char[7][];
c[0] = new char[5];
c[1] = new char[3];
//etc

Prints String with white space in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Am having a txt file. which is having line like
if(true) return true;
I need to get the sub string from preceding spaces that is
" if(true) "
and another sub string as
" retrun true; "
I am reading this line using scanner class and assign to a string. from that string am converting it into toCharArray. I have tried using toCharArray[] but the spaces are ignored. How to get the substring from the preceding spaces using toCharArray
kindly anybody help me to get a solution for this issue
Thanks in advance.
You can use StringReader:
String str = "Some String";
int numberOfChars = str.length();
StringReader sr = new StringReader(str);
char[] chars = new char[numberOfChars];
int i = 0, read = 0;
try {
while ((read = sr.read()) != -1) {
chars[i] = (char)read;
i++;
}
} catch (IOException e) {
// handle the exception
}
This will read all the characters, without skipping any of them.
EDIT:
Now that I understand what you are trying to do, I would recommend you to define a grammar for your instructions. In this way you should be able to identify these 2 separate statements or instructions. I would suggest you to use a compiler building tool for that like e.g. ANTLR.
I have found one solution by using Regular expression for this question. The answer is as follows
public class Test{
public static void main(String[] args){
String str = " TestProgram";
Pattern pattern = Pattern.compile("\\s*[a-zA-Z0-9]+$");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println(0,matcher.end());
}
}
}
Thanks

linear search for a given string in java ? Are there any better solutions? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Sorry if my question is silly but I need some help.
Well, the problem is that I am trying to learn java and was trying to make a little program
that will search through the text file for a matching string that has been inserted in the
parameter. I wanted to know which part of the program should I fix to make the method work properly or at least want to know if there is a better solution.
public String linaerSearch(String filename,String strToArrays){
String[]arrays;
File f = new File("C:\\Users\\toyman\\Documents\\NetBeansProjects\\ToyMaker\\"+filename);
String[]items = (strToArrays.split("\\s*,\\s*"));//converting the string into arrays by comma
//convert the int into string
StringBuilder build = new StringBuilder();
if(f.exists()){ //checks if the file actually exists
try(FileInputStream fis = new FileInputStream(f)){
int con; int incrementor =0;
while((con=fis.read())!=-1){
incrementor++;
char str = (char)con;
String str2 = Character.toString(str);
if(items[ ????? ].equals(str2)){
// I want to check if the string that has been passed in the parameter
// exists in the file. But I got confused at the items[ ???? ].
System.out.println("found you");
}
//System.out.println();
//convert to char and display it
System.out.print(str2);
}
}catch(Exception e){
e.printStackTrace();
}
}else{
System.out.println("The file doesn't exist. Create a new file or use a existing file");
}
return "";
}
If you want to search for some string in a text, and do it properly, it has nothing to do with Java. What you're looking for is a string searching algorithm.
Try looking in Wikipedia: http://en.wikipedia.org/wiki/String_searching_algorithm
I'd suggest going for either:
Rabin–Karp algorithm: http://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_string_search_algorithm
Knuth–Morris–Pratt algorithm: http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
They are both really good and efficient algorithms, and both are fairly easy to implement.

Reading Strings [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble with an assignment. What's happening is that a file is being read that reads numbers and validates if they're correct values. One of these values contains a letter and I'm trying to get my program to detect that and save the total value that should not be there. Here's the code. I'm reading the data as Strings and then converting the strings into doubles to be compared. I want to validate if the strings being read in are all numbers and then save that value for a later use. Does that make sense? for example the numbers have to be between 0 and 99999 and one value is 573S1, which wouldn't work because it contains an S. I want to save that value 573S1 to be printed as an error from the file at a later point in the code.
public static void validateData() throws IOException{
File myfile = new File("gradeInput.txt");
Scanner inputFile = new Scanner(myfile);
for (int i=0; i<33; i++){
String studentId = inputFile.next();
String toBeDouble = studentId;
Double fromString = new Double(toBeDouble);
if (fromString<0||fromString>99999){
System.out.println();
}
Any help would be greatly appreciated. Thanks a lot!
Edit: Here's what I get if I try to run the program.
Exception in thread "main" java.lang.NumberFormatException: For input string: "573S1"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.valueOf(Double.java:475)
at java.lang.Double.<init>(Double.java:567)
at Paniagua_Grading.validateData(Paniagua_Grading.java:23)
at Paniagua_Grading.main(Paniagua_Grading.java:6)
Because you are using Scanner on a file, Scanner can actually tell you this information with hasNextDouble.
while(inputFile.hasNext()) {
if(inputFile.hasNextDouble()) {
// the next token is a double
// so read it as a double
double d = inputFile.nextDouble();
} else {
// the next token is not a double
// so read it as a String
String s = inputFile.next();
}
}
This kind of convenience is the main reason to use Scanner in the first place.
You could try something like the method below, which will check if a string contains only digits -
private static boolean onlyDigits(String in) {
if (in == null) {
return false;
}
for (char c : in.toCharArray()) {
if (Character.isDigit(c)) {
continue;
}
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(onlyDigits("123"));
System.out.println(onlyDigits("123A"));
}
The output is
true
false

This method won't work... Is it a syntax error? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
So, I've been having issues with this. I'm trying to make this method return the first character of the string given to it, but I keep getting java.util.NoSuchElementException... I think I may be using some syntax wrong but really I have no idea. Any help?
public static char nthChar (){
Scanner sc = new Scanner(in);
String input = sc.nextLine();
char [] userCharArray = new char[input.length()];
userCharArray = input.toCharArray();
sc.close();
return userCharArray[0];
}
Note that I imported the static members of java.lang.System
I changed it to this...
public static char nthChar (){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
char [] userCharArray = input.toCharArray();
sc.close();
return userCharArray[0];
}
Still doesn't work.
This looks like the suspect to me:
sc.close();
When you close that Scanner, you are also closing System.in. Subsequent reads from a new Scanner reading from System.in will throw NoSuchElementException because the underlying stream is closed.
So you need to remove that and also look through your code and make sure you are not closing System.in elsewhere. Although usually you should close your streams when you are done with them, System.in is a special case and you don't need to (and shouldn't) close a stream that's reading from it.
For example, this will throw a NoSuchElementException:
Scanner in1 = new Scanner(System.in);
in1.close();
Scanner in2 = new Scanner(System.in);
String line = in2.nextLine(); // throws the exception

Categories