BufferedReader sometimes read text, sometimes doesn't - java

I'm trying to read from a .java the methods I have on it, also the classes, I'm using taggs to identify them and stored them, the problem is that using BufferedReader sometimes just doesn't work, the buffer skips a lot of lines for a reason that I can't understand, sometimes when checking the file by myself I just put random spaces between lines, and that fixes some parts, but I can't get the Buffer read all my text without skipping anything, my code so far is like this:
public class ReadFile {
public static void main(String[] args) {
int numclas=0,numbase=0,numbaseagr=0,numbmet=0,numag=0;
String mt="//MT";
String[] nomclass2 = new String[10];
String[] nommetodo2 = new String[50];
boolean metodo=false;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("\\Program.java"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.trim().split("\\s+");
for(int i=0;i<splited.length;i++){
System.out.println(splited[i]);
if(splited[i].equals("class")){
nomclass2[numclas]=splited[i+1];
numclas=numclas+1;
}
if (splited[i].equals(mt)){
metodo=true;
}
if (splited[i].equals("public")){
if (splited[i+1].equals("static")){
nommetodo2[numbmet]=splited[i+3];
numbmet=numbmet+1;
}
if (splited[i+1].equals("int")||splited[i+1].equals("double")||splited[i+1].equals("String")||splited[i+1].equals("boolean")){
nommetodo2[numbmet]=splited[i+2];
numbmet=numbmet+1;
}
if (splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean")){
nommetodo2[numbmet]=splited[i+1];
numbmet=numbmet+1;
}
metodo=false;
}
if ((splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean"))&&metodo){
nommetodo2[numbmet]=splited[i+1];
numbmet=numbmet+1;
metodo=false;
}
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
Now let me show you the .java I'm trying to read:
import java.text.DecimalFormat;
import java.io.*;
//Main file of the program 1
public class Program1 {
//MT
public static void main (String args []) {
DecimalFormat format=new DecimalFormat("##.##");
System.out.println("How many data do you want to insert?");
int num=Leer.Int();
Fila lista=new Fila();
Fila lista2=new Fila();
double x=0.0;
for(int i=0;i<num;i++){
x=Leer.Double();
lista.addNum(x);
}
double prom=0.0;
double desv=0.0;
prom=lista.getprom();
desv=lista.getdevst();
System.out.println("The mean for column 1 is: "+format.format(prom));
System.out.println("The Std.Dev for column 1 is: "+format.format(desv));
System.out.println("How many data do you want to insert?");
num=Leer.Int();
x=0.0;
for(int i=0;i<num;i++) {
x=Leer.Double();
lista2.addNum(x);
}
prom=0.0;
desv=0.0;
prom=lista2.getprom();
desv=lista2.getdevst();
System.out.println("The mean for column 2 is: "+format.format(prom));
System.out.println("The Std.Dev for column 2 is: "+format.format(desv));
}
}
And the result when I print the array
Date:
12/12/12
import
java.text.DecimalFormat;
//Main
file
of
the
program
1
//MT
DecimalFormat
format=new
DecimalFormat("##.##");
so on...
See how in the //MT the Buffer skips a lot of lines, a lot of this is happening (see how it ignores the first lines of the program), and I don't know how to fix it, because sometimes when I try to "fix it" and add some spaces in the lines, I get a nullpointer and the program ends.
Any help will be appreciated, thank you.

This is just a partial answer - at the very least your program is skipping every other line:
while ((read = in.readLine()) != null)
will read a line from the file. The line is immediately discarded because the immediately following statement:
read = in.readLine();
reads and processes the next line from the file.
(also, 'splited' should be 'splitted' along with numerous other spelling mistakes but they're not really affecting your program, just it's readability :-))

Related

Input a text file through command line in java

I am trying to write a program that inputs a text file through the command line and then prints out the number of words in the text file. I've spent around 5 hours on this already. I'm taking an intro class using java.
Here is my code:
import java.util.*;
import java.io.*;
import java.nio.*;
public class WordCounter
{
private static Scanner input;
public static void main(String[] args)
{
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
openFile();
readRecords();
closeFile();
}
public static void openFile()
{
try
{
input = new Scanner(new File(file));
}
catch (IOException ioException)
{
System.err.println("Cannot open file.");
System.exit(1);
}
}
public static void readRecords()
{
int total = 0;
while (input.hasNext()) // while there is more to read
{
total += 1;
}
System.out.printf("The total number of word without duplication is: %d", total);
}
public static void closeFile()
{
if (input != null)
input.close();
}
}
Each way I've tried I get a different error and the most consistent one is "cannot find symbol" for the file argument in
input = new Scanner(new File(file));
I'm also still not entirely sure what the difference between java.io and java.nio is so I have tried using objects from both. I'm sure this is an obvious problem I just can't see it. I've read a lot of similar posts on here and that is where some of my code is from.
I've gotten the program to compile before but then it freezes in command prompt.
java.nio is the New and improved version of java.io. You can use either for this task. I tested the following code in the command line and it seems to work fine. The "cannot find symbol" error message is resolved in the try block. I think you were confusing the compiler by instantiating a File object named file twice. As #dammina answered, you do need to add the input.next(); to the while loop for the Scanner to proceed to the next word.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class WordCounter {
private static Scanner input;
public static void main(String[] args) {
if(args.length == 0) {
System.out.println("File name not specified.");
System.exit(1);
}
try {
File file = new File(args[0]);
input = new Scanner(file);
} catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
int total = 0;
while (input.hasNext()) {
total += 1;
input.next();
}
System.out.printf("The total number of words without duplication is: %d", total);
input.close();
}
}
Your code is almost correct. Thing is in the while loop you have specified the terminating condition as follows,
while (input.hasNext()) // while there is more to read
However as you are just increment the count without moving to the next word the count just increases by always counting the first word. To make it work just add input.next() into the loop to move to next word in each iteration.
while (input.hasNext()) // while there is more to read
{
total += 1;
input.next();
}

Java Scanner Delimeter not working as I expected

I have got a question about a code I have written
package salescities;
import java.io.File;
import java.util.Scanner;
public class SalesCities {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double totalSales = 0;
int count = 0;
int missingCount = 0;
String line;
File file;
Scanner input;
try {
file = new File("sales.txt");
input = new Scanner(file);
input.useDelimiter(":");
while (input.hasNextLine()) {
input.next();
line = input.nextLine();
try{
totalSales += Double.parseDouble(line);
count++;
}
catch(IllegalArgumentException e){
missingCount++;
}
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(totalSales + " " +missingCount);
}
}
And the file im trying to read is like this
New York: 23.5678
New Jersey: no reports
Rio de Janeiro: 12.3654
When i run the program however it prints out 0.0 3 like all is missing.
The problem is when i run the debugger to see whats happening to line so parseDouble isn't functioning and i saw that line is a string that has this
: 23.5678
and I don't understand why if I'm using ":" as delimeter. I expected only the number without the colon. Can someone answer me?
ps: this is an exercise from a book that's quite simple but the book uses a class TextIO that is implemented by them. just wanted to try scanner instead of their code.
Scanner#nextLine grabs the rest of the line, regardless of the delimiter.
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. — Scanner#nextLine

Infinite loop during file reading and String.split() not working properly

I have a text file admin.dat which looks like this:
blackranger|sdasdasdasd23123|1000
blueranger|sdasdasdasdwhhh22|1000
brownranger|lppsadospd123|1000
I am trying to read every line, using | as my delimiter and outputting to the console every section.
Code:
package testing;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
Scanner filereader = null;
try {
filereader = new Scanner(new File("./src/testing/players.dat"));
String data;
while(filereader.hasNextLine()) {
String foo = "abc|123|a213";
String[] bar = foo.split("|");
for (int i = 0; i < 3; i++) {
System.out.println(bar[i]);
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error while reading file");
} finally {
if (filereader != null) {
filereader.close();
}
}
}
}
Expected Outcome:
blackranger
sdasdasdasd23123
1000
blueranger
sdasdasdasdwhhh22
1000
brownranger
lppsadosph123
1000
Actual Outcome:
a // infinite loop
b
a
b
a
b
a
b
a
b
Why am I getting an infinite loop which prints a b forever?
You should escape the character | because it has special meaning in regex
foo.split("\\|");
But firstly, assign foo with value that you read from the file, not by hard-coded it:
String foo = filereader.nextLine();
You never read from the fileReader inside the while loop, so while(filereader.hasNextLine()) will always be true, and it makes sense that the loop will never end. What surprised me is that it looked like you had code that did read from the fileReader inside of the loop but commented it out. Why?
Solution: don't do this. Make sure to change the test condition inside the while loop, else the while loop will never end.
String foo = filereader.nextLine();
String[] bar = foo.split("\\|");
instead of
String foo = "abc|123|a213";
String[] bar = foo.split("|");

Reading a Text File in Java and Converting to Multiple Vectors

I am fairly new to Java, and I am trying to make it read a file.
I have a data text file that needs to be imported into Java as arrays.
The first row of data file is the names row. All the variables has their names in the first row and the data are clustered in the columns. I just want to import this into Java and to be able to export all the variables as I want, just as if they were vectors in MATLAB. So basically we acquire the data and tag each vector. I need the code to be as generic as possible, so it should read a variable number of columns and rows. I was able to create the array using a non-efficient method I believe. Now I need to divide the array into multiple arrays and then convert them to numbers. But I need to group the number according to the vector they belong in.
The text file is created from an Excel spreadsheet, so it basically has the columns for different measurements, which will create the vectors. Each column in another vector which contains the data in the rows.
I searched a lot of code trying to implement, but it came to a point I cannot proceed without help. Can someone possibly tell me how to proceed in any sense. Maybe even improve the reading part also, because I know it is not the best way to do like this in Java. Here is what I have in hand:
package Testing;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class Read1 {
public static void main(String[] args) {
try {
FileReader fin = new FileReader("C:/jade/test/Winter_Full_clean.txt");
BufferedReader in = new BufferedReader(fin);
String str = "";
int count = 0;
String line;
while ((line=in.readLine()) != null) {
if (count==0) {
str = line;
}
else if (in.readLine()!=null) {
str = str + line;
}
count++;
}
in.close();
//System.out.printf(str);
System.out.print(tokens);
} catch (Exception e) {
System.out.println("error crap" + e.getClass());
}
}
//{
// Path yourFile = Paths.get("C:/jade/test/Winter_Full_clean.txt");
// Charset charset = Charset.forName("UTF-8");
// List<String> lines = null;
// try {
// lines = Files.readAllLines(yourFile, charset);
// } catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
// String[] arr = lines.toArray(new String[lines.size()]);
// System.out.println(arr);
//}
}
I have some code that is functional and reads a text file into an array and split on tabs ( its a tsv file). You should be able to adapt this as a starting point to read in your initial data, and then based upon the data contained within your array, alter your logic to suit:
try (BufferedReader reader = new BufferedReader(new FileReader(path))) { //path is a String pointing to the file
int lineNum = 0;
String readLine;
while ((readLine = reader.readLine()) != null) { //read until end of stream
if (lineNum == 0) { //Skip headers, i.e. start at line 2 of your excel sheet
lineNum++;
continue;
}
String[] nextLine = readLine.split("\t"); //Split on tab
for (int x = 0; x < nextLine.length; x++) { //do something with ALL the lines.
nextLine[x] = nextLine[x].replace("\'", "");
nextLine[x] = nextLine[x].replace("/'", "");
nextLine[x] = nextLine[x].replace("\"", " ");
nextLine[x] = nextLine[x].replace("\\xFFFD", "");
}
//In this example, to access data for a certain column,
//call nextLine[1] for col 1, nextLine[2] for col 2 etc.
} //close your loop and go to the next line in your file
} //close your resources.

Reading a string with new lines from console java

I want to read this string (from console not file) for example:
one two three
four five six
seven eight nine
So I want to read it per line and put every line in an array.
How can I read it? Because if I use scanner, I can only read one line or one word (nextline or next).
what I mean is to read for example : one two trhee \n four five six \n seven eight nine...
You should do by yourself!
There is a similer example:
public class ReadString {
public static void main (String[] args) {
// prompt the user to enter their name
System.out.print("Enter your name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
userName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the name, " + userName);
}
} // end of ReadString class
To answer the question as clarified in the comment on the first answer:
You must call Scanner's nextLine() method once for each line you wish to read. This can be accomplished with a loop. The problem you will inevitably encounter is "How do I know big my result array should be?" The answer is that you cannot know if you do not specify it in the input itself. You can modify your programs input specification to require the number of lines to read like so:
3
One Two Three
Four Five
Six Seven Eight
And then you can read the input with this:
Scanner s = new Scanner(System.in);
int numberOfLinesToRead = new Integer(s.nextLine());
String[] result = new String[numberOfLinesToRead];
String line = "";
for(int i = 0; i < numberOfLinesToRead; i++) { // this loop will be run 3 times, as specified in the first line of input
result[i] = s.nextLine(); // each line of the input will be placed into the array.
}
Alternatively you can use a more advanced data structure called an ArrayList. An ArrayList does not have a set length when you create it; you can simply add information to it as needed, making it perfect for reading input when you don't know how much input there is to read. For example, if we used your original example input of:
one two trhee
four five six
seven eight nine
You can read the input with the following code:
Scanner s = new Scanner(System.in);
ArrayList<String> result = new ArrayList<String>();
String line = "";
while((line = s.nextLine()) != null) {
result.add(line);
}
So, rather than creating an array of a fixed length, we can simply .add() each line to the ArrayList as we encounter it in the input. I recommend you read more about ArrayLists before attempting to use them.
tl;dr: You call next() or nextLine() for each line you want to read using a loop.
More information on loops: Java Loops
Look at this code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class SearchInputText {
public static void main(String[] args) {
SearchInputText sit = new SearchInputText();
try {
System.out.println("test");
sit.searchFromRecord("input.txt");
System.out.println("test2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void searchFromRecord(String recordName) throws IOException {
File file = new File(recordName);
Scanner scanner = new Scanner(file);
StringBuilder textFromFile = new StringBuilder();
while (scanner.hasNext()) {
textFromFile.append(scanner.next());
}
scanner.close();
// read input from console, compare the strings and print the result
String word = "";
Scanner scanner2 = new Scanner(System.in);
while (((word = scanner2.nextLine()) != null)
&& !word.equalsIgnoreCase("quit")) {
if (textFromFile.toString().contains(word)) {
System.out.println("The word is on the text file");
} else {
System.out.println("The word " + word
+ " is not on the text file");
}
}
scanner2.close();
}
}

Categories