So I have this method here that should return the amount of lines in a csv file. Pretty simple right? Thing is instead of returning the amount of lines in the csv file(in this case 15) it returns 66. I honestly have know Idea why this would happen. I checked the csv file and verified that it is indeed 15 lines long with no empty lines. Also does anyone know why my Jpanes wont display without those three lines commented lines, my ide says the variables aren't in use anywhere.
public static int getLineCount(){
int line=0;
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String data =inputStream.next();//this line is useless but the program doesn't display with out it
String[] values = data.split(",");//this line is useless but the program doesn't display with out it
i++;//this line is useless but the program doesn't display with out it
line++;
}
}catch(FileNotFoundException e){
e.printStackTrace();
}
return line;
}
Use BufferedReader instead of Scanner:
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
while(reader.readLine() != null){
line++;
}
public static int getLineCount(){
String csvFilePath = "C:\\Users\\uzochi\\desktop\\txt.csv";
String line = "";
int numberOfLines=0;
try {
BufferedReader br = new BufferedReader(new FileReader(csvFilePath));
while (( line = br.readLine()) != null) {
numberOfLines++;
}
}catch(FileNotFoundException e){
//
}catch (IOException ex) {
//
}
return numberOfLines;
}
Related
I read about someone having troubles with BufferedReader: the reader simply do not read the first lines. I have instead the opposite problem. For example, in a text file with 300 lines, it arrives at 200, read it half of it and then the following string is given null, so it stops.
private void readerMethod(File fileList) throws IOException {
BigInteger steps = BigInteger.ZERO;
BufferedReader br = new BufferedReader(new FileReader(fileList));
String st;
//reading file line by line
try{
while (true){
st = br.readLine();
if(st == null){
System.out.println("Null string at line " + steps);
break;
}
System.out.println(steps + " - " + st);
steps = steps.add(BigInteger.ONE);
}
}catch(Exception e){
e.printStackTrace();
}
finally{
try{
br.close();
}catch(Exception e){}
}
}
The output of the previous slice of code is as expected until it reaches line 199 (starting from 0). Consider a file with 300 lines.
...
198 - 3B02D5D572B66A82F9D21EE809320DB3E250C6C9
199 - 6E2C69795CB712C27C4097119CE2C5765
Null string at line 200
Notice that, all lines have the same length, so in this output line 199 is not even complete. I checked the file text, and it's correct: it contains all 300 lines and they are all of the same length. Also, in the text there are only capitals letters and numbers, as you can see.
My question is: how can i fix this? I need that the BufferedReader read all the text, not just a part of it.
As someone asked i add here the remaining part of the code. Please notice that all capital names are constant of various type (int, string etc).
This is the method that is called by the main thread:
public void init(){
BufferedWriter bw = null;
List<String> allLines = createRandomStringLines(LINES);
try{
String fileName = "SHA1_encode_text.txt";
File logFile = new File(fileName);
System.out.println(logFile.getCanonicalPath());
bw = new BufferedWriter(new FileWriter(logFile));
for(int i = 0; i < allLines.size(); i++){
//write file
String o = sha1FromString(allLines.get(i));
//sha1FromString is a method that change the aspect of the string,
//replacing char by char. Is not important at the moment.
bw.write(o + "\n");
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
bw.close();
}catch(Exception e){}
}
}
The method that create the list of random string is the following. "SYMBOLS" is just a String contains all avaiable chars.
private List<String> createRandomStringLines(int i) {
List<String> list = new ArrayList<String>();
while(i!=0){
StringBuilder builder = new StringBuilder();
int count = 64;
while (count-- != 0) {
int character = (int)(Math.random()*SYMBOLS.length());
builder.append(SYMBOLS.charAt(character));
}
String generatedString = builder.toString();
list.add(generatedString);
i--;
}
return list;
}
Note that, the file written is totally correct.
Okay, thanks to the user ygor, i manage to resolve it. The problem was that the BufferReader stars his job when the BufferWriter isn't closed yet. It was sufficient to move the command line that require the reader to work, after the bufferWriter.close() command.
I'm in a beginning programming class, and seem to be having a major issue with searching a text file. What my code should do, based on the assignment:
Accept input, in this case a name and place that input into a .txt file
Allow the user to search for a name, or part of a name, and return all lines with matching text.
I have the input portion of the assignment complete, and am on the verge on completing the retrieval portion, but my code only searches the first line of the .txt file. I am able to print out all lines of the .txt file, and if I search for the name in Line 1 of the .txt file, it will print the line correctly. My issue comes when I am searching for a name that is not on Line 1. Below is my code:
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
if (choice == 2 && retrieve.equalsIgnoreCase("YES") || retrieve.equalsIgnoreCase("Y"))
{
while (retrieve2.equalsIgnoreCase("YES") || retrieve2.equalsIgnoreCase("Y"))
{
FileReader reader = new FileReader("Name_Index.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
System.out.println ("Enter a string of characters in which to search by or enter \"all names\" f$
search_term = gatherInput();
System.out.println("Search results include: ");
ArrayList<String> list = new ArrayList<String>();
Scanner inFile = new Scanner (new File("Name_Index.txt"));
inFile.useDelimiter(",");
while (inFile.hasNextLine())
{
list.add(inFile.nextLine());
}
Collections.sort(list);
if (search_term.equalsIgnoreCase("all names"))
{
for (String temp : list)
{
System.out.println(temp);
}
}
else if (line.toLowerCase().contains(search_term.toLowerCase()))
{
System.out.println(line);
bufferedReader.close();
}
System.out.println("End!");
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve2=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
System.out.println("Thank you, come again!");
}
}
public static String gatherInput()
{
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
return user_input;
}
}
I have tried expanding the while (inFile.hasNextLine()) loop to include the second "if" statement, however that creates an issue for the "all names" search - it returns the entire list multiple times (however many lines are in the file). I have even tried creating another while (inFile.hasNextLine()) loop within the second "if" statement, and there is no difference in outcome.
I'm so frustrated at this point, because I've been working on this code for over a week, and have reviewed all of my notes and lecture recordings for this assignment with no help. Any insight would be much appreciated.
You are reading only 1 line of the file
String line = bufferedReader.readLine();
Why don't you read all lines and store them in a List;
List<String> lines = new ArrayList<>();
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
Then to print all lines containing a substring ignorecase:
lines.stream().filter(l -> l.toLowerCase().contains(search_term.toLowerCase))
.forEach(s -> System.out.println(s));
You need to loop the readLine()
For example:
File f = new File(ruta);
if(!f.exists()) //Error
else {
#SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
//line = the next line
}
}
I am facing some problem while reading the contents of file.
Although program is reading contents, it is skipping odd line data from file.
Example of file:
Czech Republic____06092015_091108
France____06092015_060256
Greece____06092015_073528
Hungary____06092015_093424
India____06092015_120741
Indonesia____06092015_140940
Kazakhstan____06092015_095945
Mexico____06092015_061522
Turkey____06092015_100457
But the output is:
java.io.DataInputStream#1909752
France____06092015_060256
Hungary____06092015_093424
Indonesia____06092015_140940
Mexico____06092015_061522
I don't understand why it is giving output as in this format.
I have line separator in input file, can it be causing the problem?
public class tst {
// Main method
public static void main(String args[]) {
// Stream to read file
FileInputStream fin;
int k = 0;
try {
// Open an input stream
fin = new FileInputStream(
"C:/Users/BOT2/Desktop/MC_WIth_DATA_Files.txt");
DataInputStream in1 = new DataInputStream(fin);
// Read a line of text
System.out.println(new DataInputStream(fin));
// Close our input stream
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
while (br1.readLine() != null) {// System.out.println(k);k++;
System.out.println(br1.readLine());
}
br1.close();
fin.close();
}
// Catches any error conditions
catch (IOException e) {
System.err.println("Unable to read from file");
System.exit(-1);
}
}
}
You have two errors. First, you print out the dataStream object for some reason. Get rid of :
// Read a line of text
System.out.println( new DataInputStream(fin) );
Next, you throw away lines of text. Try this instead:
String line;
while ((line = br1.readLine()) != null){
System.out.println(line);
}
The first line is printed by:
System.out.println( new DataInputStream(fin) );
it gives you te result of new DataInputStream(fin).toString()
The next lines are printed in this format, bacause you read two lines per loop:
first line while (br1.readLine() != null){ and second line: System.out.println(br1.readLine()); }
So you have to change your code to:
String line;
while ((line =br1.readLine()) != null){//System.out.println(k);k++;
System.out.println(line );
}
br1.close();
fin.close();
The problem is here
while (br1.readLine() != null){
System.out.println(br1.readLine());
}
br1.close();
fin.close();
}
When you call br1.readLine() it reads out the current line and move the cursor position to point to the next line. You are calling this method twice causing you to skip alternative lines. You should call readLine() only once per iteration.
i suggest cleaner code so you and whoever reads it will understand immediately what you are doing.
Try this :
Scanner read;
try{
read=new Scanner(new FileReader("your path"));
while(read.hasNext()){
System.out.println(read.nextLine);
}
read.close();
}
catch(FileNotFoundException e){
}
So I'm having an issue reading a text file into my program. Here is the code:
try {
InputStream fis = new FileInputStream(targetsFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
//while(br.readLine()!=null){
for (int i = 0; i < 100; i++) {
String[] words = br.readLine().split(" ");
int targetX = Integer.parseInt(words[0]);
int targetY = Integer.parseInt(words[1]);
int targetW = Integer.parseInt(words[2]);
int targetH = Integer.parseInt(words[3]);
int targetHits = Integer.parseInt(words[4]);
Target a = new Target(targetX, targetY, targetW, targetH, targetHits);
targets.add(a);
}
br.close();
} catch (Exception e) {
System.err.println("Error: Target File Cannot Be Read");
}
The file I am reading from is 100 lines of arguments. If I use a for loop it works perfectly. If I use the while statement (the one commented out above the for loop) it stops at 50. There is a possibility that a user can run the program with a file that has any number of lines, so my current for loop implementation won't work.
Why does the line while(br.readLine()!=null) stop at 50? I checked the text file and there is nothing that would hang it up.
I don't get any errors from the try-catch when I use the while loop so I am stumped. Anyone have any ideas?
also very comprehensive...
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
You're calling br.readLine() a second time inside the loop.
Therefore, you end up reading two lines each time you go around.
You can use a structure like the following:
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
In case if you are still stumbling over this question.
Nowadays things look nicer with Java 8:
try {
Files.lines(Paths.get(targetsFile)).forEach(
s -> {
System.out.println(s);
// do more stuff with s
}
);
} catch (IOException exc) {
exc.printStackTrace();
}
Thank you to SLaks and jpm for their help. It was a pretty simple error that I simply did not see.
As SLaks pointed out, br.readLine() was being called twice each loop which made the program only get half of the values. Here is the fixed code:
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
String words[]=new String[5];
String line=null;
while((line=br.readLine())!=null){
words=line.split(" ");
int targetX=Integer.parseInt(words[0]);
int targetY=Integer.parseInt(words[1]);
int targetW=Integer.parseInt(words[2]);
int targetH=Integer.parseInt(words[3]);
int targetHits=Integer.parseInt(words[4]);
Target a=new Target(targetX, targetY, targetW, targetH, targetHits);
targets.add(a);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
Thanks again! You guys are great!
Concept Solution:br.read() returns particular character's int value so loop
continue's until we won't get -1 as int value and Hence up to there it prints
br.readLine() which returns a line into String form.
//Way 1:
while(br.read()!=-1)
{
//continues loop until we won't get int value as a -1
System.out.println(br.readLine());
}
//Way 2:
while((line=br.readLine())!=null)
{
System.out.println(line);
}
//Way 3:
for(String line=br.readLine();line!=null;line=br.readLine())
{
System.out.println(line);
}
Way 4:
It's an advance way to read file using collection and arrays concept
How we iterate using for each loop.
check it here
http://www.java67.com/2016/01/how-to-use-foreach-method-in-java-8-examples.html
In addition to the answer given by #ramin, if you already have BufferedReader or InputStream, it's possible to iterate through lines like this:
reader.lines().forEach(line -> {
//...
});
or if you need to process it with given order:
reader.lines().forEachOrdered(line -> {
//...
});
I am trying to read values from a text file. There are 6 doubles on each line for the file.
I created a getBufReader method
public BufferedReader getBufReader(String filename, int rawName){
if(D) Log.i(TAG, "GETTING FILE");
BufferedReader bufReader = null;
// open the file for reading
InputStream instream = getResources().openRawResource(rawName);
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
bufReader = new BufferedReader(inputreader);
}
// close the file again
try{instream.close();}
catch (Exception e) {
if(D) Log.e(TAG, "Unable to Close " + filename);}
return bufReader;
}
Each line in the file is supposed to be an entire row in my 2D array. I tried to get a line, tokenize it and put that in the array. But the program keeps crashing. The DDMS Log does does not produce a bunch or errors as I expect
public void getData(){
int rawName = R.raw.values_doubles;
BufferedReader reader_0 = getBufReader(strData2, rawName );
//2D array of x rows and y columns to store the data
//
double[][] Data_temp = new double[size_x][size_y];
String line = null;
StringTokenizer Strtoken;
for(i=0;i<size_x;i++){
try {line = reader_0.readLine();}catch (IOException e) {}
if(line != null){
Strtoken = new StringTokenizer(line);
for(j=0;j<size_y;j++){
if (Strtoken.hasMoreTokens()){
Data_temp[i][j] = Double.parseDouble(Strtoken.nextToken());
CommandsAdapter.add(""+Data_temp[i][j]+" ");
}}
}
CommandsAdapter.add("\n");}}
Please help
Also, I get errors if I don't surroung reader_0.readLine() with try/catch.
I would create a FileInputStream and a Buffered Reader. I am writing this from my lap top so I cannot test this code but this should give you a general idea (my first app saved data on seperate lines in a text file and I could read and write to it using this method)
NOTE this requires you to know how many lines are in your file
FileInputStream fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(fis);
Double myArray[][] = new Double [Text_File_Lines][6];
StringBuffer buffer = new StringBuffer();
int x = 0;
int y = 0;
while (reader.readLine() != -1) { //indicating end of file
while (reader.nextChar != '\n' ) { //indicating new line
while (reader.nextChar != ' ' ) { //indicating no space character
buffer.append(reader.nextChar());
}
Double[y][x] = Double.parseDouble(buffer.toString()); //Parse double and add it to array
buffer = null; //restore buffer to null
x++;
}
y++;
}
PLEASE NOTE THIS IS VERY SLOPPY CODE THAT ALMOST DEFINITELY WONT WORK this is just to get you started and I will post my working code when I get home from work.