I am trying to create a program that counts lines of code, where the commented lines are not included. I have come up with the code below, and its almost working completely, however when gets the strings from the file, it seems to be skipping the first line. Any help would be greatly appreciated!
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.*;
public class locCounter
{
public locCounter(String filename)
{
System.out.println("Counting lines in " + filename + "...");
}
public static void main(String[] args) throws FileNotFoundException
{
boolean isEOF = false;
System.out.println( "What file would you like to count the lines of code for?" );
String programName = "test1.txt";
//System.out.println(programName);
locCounter countLines = new locCounter(programName);
try ( BufferedReader reader = new BufferedReader( new FileReader( programName )))
{
String line = reader.readLine();
int counter = 0;
while ((line = reader.readLine()) != null)
{
line = line.trim();
System.out.println(line);
if (line.startsWith("//"))
{
counter = counter;
}
else
{
counter = counter + 1;
}
}
System.out.println(counter);
reader.close();
}
catch (FileNotFoundException ex)
{
System.out.println("The file was not found in the current directory.");
}
catch (IOException e)
{
System.exit(0);
}
}
}
test1.txt
This file has one line of code
// This comment should not count
This file now has two lines of code
// Another comment that shouldn't be counted
}
A total of 4 lines should be counted.
Output
What file would you like to count the lines of code for?
Counting lines in test1.txt...
// This comment should not count
This file now has two lines of code
// Another comment that shouldn't be counted
}
A total of 4 lines should be counted.
3
Remove this line from your code:
String line = reader.readLine();
It basically reads the line. And later on you have 'while ((line = reader.readLine()) != null)' inside the while condition again, so you read 2 lines in total, but only start processing from second line.
AS #admix has said, your problem is that you should replace this line of code
String line = reader.readLine();
with
String line;
By now, your problem has been solved.
As I can see you use JDK7, so you can write your read file code with fewer lines.
Path path = Paths.get(programName);
try {
try (BufferedReader reader = Files.newBufferedReader(path)){
String line;
while ((line = reader.readLine()) != null) {
//process each line in some way
}
}
} catch (IOException e) {
e.printStackTrace();
}
or even cleaner version
Path path = Paths.get(programName);
try {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
//process each line in some way
}
} catch (IOException e) {
e.printStackTrace();
}
In addition, your program will be more elegant is you remove those lines, which is unnecessary.
if (line.startsWith("//"))
{
counter = counter;
}
Related
I am trying to write a program that will read line n of a provided text file, using a BufferedReader, and convert this line's contents into an int. This is the code I am currently using, but it fails to output an int:
BufferedReader reader = null;
int LineContent;
try {
File file = new File("C:\\Users\\Admin\\Desktop\\SAVEdata\\Save.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
LineContent = Integer.parseInt(line);
if (LineContent == 0) {
CHRSelectWorld w = new CHRSelectWorld();
Greenfoot.setWorld(w);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
You are trying to read and parse every line in your file. If you want nth line, you can use Files class
String line = Files.readAllLines(Paths.get("file.txt")).get(n);
It will work well for files of small-medium size.
long n = 42L;
Path path = Paths.get(
"C:\\Users\\Admin\\Desktop\\SAVEdata\\Save.txt");
Optional<String> line =
Files.lines(path, Charset.defaultCharset())
.skip(n - 1)
.findFirst();
if (line.isEmpty()) {
System.out.println("Insufficient lines, less than " + n);
}
System.out.println(line.orElse("(No line found)");
The class Files has many goodies, and with streams it is almost a one-liner.
I have read a content from a file which is in my local system.It is in float type.So while printing the output I could not get value before the decimal point.What needs to be included so that i will get an exact output.
I want the output like 1.68765 But I am getting .68765
Also i need to append output from another file with this out.
Content of the file will be like this but without double line spaces inbetween.Next to each other but in next next line
1
.
6
8
7
6
5
Here is my code
package testing;
import java.io.*;
class read {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("D:/Movies/test.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
line = br.readLine();
System.out.println(line);
}
} finally {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
As you may see, you're skipping the first line by using the following. You're reading two lines before printing one so the first is skipped.
String line = br.readLine();
while (line != null) {
line = br.readLine();
System.out.println(line);
}
Solution
StringBuilder sb = new StringBuilder();
String line;
while ((line=br.readLine()) != null) {
sb.append(line);
}
float myFloat = Float.valueOf(sb.toString());
Assign the value of the line from the file directly in your loop test. This will save you from headaches and is way more intuitive.
Now since you already have a StringBuilder object, I suggest you append all the lines and then cast its value to a float.
String line = br.readLine(); had read the first line ,use
String line = "";
I suggest using the scanner class to read your input and the nextFloat class to get the next floating point number -
Scanner scanner = new Scanner(new File("D:/Movies/test.txt"));
while(scanner.hasNextFloat()) {
System.out.println(scanner.nextFloat());
}
Basicay you are skipping first line as #yassin-hajaj mentioned, you can solve this in 2 ways:
In JDK8 it would look like this:
Stream<String> lines = Files.lines(Paths.get("D:/Movies/test.txt"));
String valueAsString = lines.collect(Collectors.joining()); // join all characters into a string
Float value = Float.valueOf(valueAsString);// parse it to a float
System.out.printf("%.10f", value); // will print vlaue with 10 digits after comma
Or you can do it by (JDK7+):
StringBuilder sb = new StringBuilder();
try ( BufferedReader br = new BufferedReader(new FileReader("D:/Movies/test.txt"))){ // this will close are streams after exiting this block
String line;
while ((line = br.readLine())!=null) { // read line and assign to line variable
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("F:/test.txt"));
try {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} finally {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can also put the readLine() method within the while condition.
Also, float may not be printed the way you expect, ie, fewer digits will be displayed.
public class Reader {
public static void main(String[] args) throws IOException, NumberFormatException {
BufferedReader br = new BufferedReader(new FileReader("D:/test.txt"));
String line = null;
while ((line = br.readLine()) != null)
System.out.println(Double.parseDouble(line));
br.close();
}
}
Sample output:
1.68765
54.4668489
672.9821368
I want to extract the first String in a file using the delimiter ",".
Why does this code generate a number of lines greater than one?
public static void main(String[] args) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("irisAfter.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.split(",");
for (int i =0; i<splited.length;i++) {
System.out.println(splited[0]);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) { e.printStackTrace(); }
}
}
You are printing inside a loop. That's why it is printing multiple times (if that's what you're asking).
String[] splited = read.split(",");
System.out.println(splited[0]);
will just do
EDIT: As Abishek also mentioned, don't read = in.readLine(); again inside your while loop since by doing so you are skipping a line.
while ((read = in.readLine()) != null) {
String[] splited = read.split(",");
System.out.println(splited[0]);
}
What do you mean by number of lines superior to the original ones
If you are using splited[0], why are you keeping inside a loop. It will always get you same string
Not sure why your code works that way but you might try Scanner with a delimeter. Try:
Scanner sc = new Scanner( new File("myNumbers")).useDelimiter(",");
String firstString = sc.next();
/// check for null..
You read in every line from "irisAfter.txt", then split each line on "," into multiple elements, then print out the first element of that line on its own line as many times as there are elements in the line. Multiple lines*multiple elements per line = more lines in output than in input.
Change
for (int i =0; i<splited.length;i++) {
System.out.println(splited[0]);
}
to
if (splited.length > 0)
{
System.out.println(splited[0]);
}
That way you print out the first element of every line on its own line only one time and only if there actually is a first element.
You are also skipping every other line. If you don't want to do that, remove the line
read = in.readLine();
just below
while ((read = in.readLine()) != null) {.
(You are now reading in a line and then reading in the next line, discarding the first read in line. Then you process that second line, after which the loop starts again, you read in the third line, then read in the fourth line, discarding the third, etc. etc.)
if you modify your code like this, you should get the result you expect.
public static void main(String[] args) {
BufferedReader in = null;
try {
String[] splited;
in = new BufferedReader(new FileReader("irisAfter.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
splited = read.split(",");
}
System.out.println(splited[0]);
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
}
I'm writing a code that uses an input file called InvetoryReport.txt in a program I am supposed to create that is supposed to take this file, and then multiply two pieces of data within the file and then create a new file with this data. Also at the beginning of the program it is supposed to ask you for the name of the input file. You get three chances then it is to inform you that it cannot find it and will now exit, then stop executing.
My input file is this
Bill 40.95 10
Hammer 1.99 6
Screw 2.88 2
Milk .03 988
(The program is supposed to multiply the two numbers in the column and create a new column with the sum, and then under print another line like this
" Inventory Report
Bill 40.95 10 409.5
Hammer 1.99 6 11.94
Screw 2.88 2 5.76
Milk .03 988 29.64
Total INVENTORY value $ 456.84"
and my program I have so far is this
package textfiles;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class LookOut{
double total = 0.0;
String getFileName(){
System.out.printIn("Type in file name here.");
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
return str;
}
void updateTotal(double d){
total = total + d;
}
double getLineNumber(int String_line){
String [] invRep = line.split(" ");
Double x = double.parseDouble(invRep[1]);
Double y = double.parseDouble(invRep[2]);
return x * y;
}
void printNewData(String = newData) {
PrintWriter pW = new PrintWriter ("newData");
pw.print(newData);
pw.close;
}
public static void main(String[] args){
String str = ("Get file name");
String str = NewData("InventoryReport/n");
File file = new File(str);
Scanner s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
double data = getLineNumber(line);
update total(data);
NewData += line + " " + data + "/n";
Print NewData(NewData);
}
}
}
I'm getting multiple error codes that I just cant seem to figure out.
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Despite your best intentions you are in fact missing a '}'. Note that you haven't escaped the Try block before the catch. I imagine this is because you confused the closing } for the while statement as the closing } for the try block. Do this instead:
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
}
}
catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Also, your indentation is ALL OVER THE PLACE. This should be a lesson to you in why you should format your code properly! It is so easy to miss simple syntax errors like that if you're not formatting properly. It's also hard for others to read your code and figure out what's wrong with it.
I am reading each line of the file in the below way
BufferedReader in = new BufferedReader(new FileReader(inFile));
while (null != (line = in.readLine())) {
}
I want to do some validation in the first line and last line alone. Is there any
way to check if it's a first line and last line inside the while loop
while (null != (line = in.readLine())) {
if(firstlineoffile) {
}
else if (lastlineoffile) {
}
else
{
}
}
Cool question. I played a bit round it and here's an SSCCE, just copy'n'paste'n'run it.
package com.stackoverflow.q2292917;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class Test {
public static void main(String... args) throws IOException {
// Create test file.
File file = new File("/test.txt");
PrintWriter writer = new PrintWriter(file);
writer.println("line 1");
writer.println("line 2");
writer.println("line 3");
writer.println("line 4");
writer.println("line 5");
writer.close();
// Read test file.
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String next, line = reader.readLine();
for (boolean first = true, last = (line == null); !last; first = false, line = next) {
last = ((next = reader.readLine()) == null);
if (first) {
System.out.println("first line: " + line);
} else if (last) {
System.out.println("last line: " + line);
} else {
System.out.println("normal line: " + line);
}
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
// Delete test file.
file.delete();
}
}
Output:
first line: line 1
normal line: line 2
normal line: line 3
normal line: line 4
last line: line 5
I however question the readability and interpretability by starters... ;)
String currentLine = in.readLine();
String nextLine = in.readLine();
boolean hasStarted = false;
while(null != currentLine){
if(!hasStarted){
//first line.
hasStarted = true;
}
//all your processing here.
if(null == nextLine){
//last line, cause there's nothing else coming up
}
currentLine = nextLine;
nextLine = in.readLine();
}
if you add a count, and rearrange your code a little, this should work (I haven't tested this so there may be syntax errros):
int count = 0;
String line = in.readLine();
while (line!=null) {
String currLine = line;
if(count==0){
//currLine is the first line
}
line = in.readLine();
if(line==null){
//currLine is the last line
}
if(count>0 && line!=null){
//do something with lines in between
System.out.println(currLine);
}
count++;
}
public class Vomitfirstline {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("Path"));
br.readLine();
{
while ((sCurrentLine = br.readLine()) != null)
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Someone might well come up with a more elegant solution than this, but here we go:
boolean isFirstLine = true;
do{
String line = in.readLine();
if(isFirstLine){
//this is the first line
isFirstLine = false;
}
else if(line==null){ //previous line was the last line
in.reset();
line = in.readLine();
//do last line specific stuff
break;
}
else {
//do stuff for lines in between
}
in.mark(100);
}while (line!=null);
I haven't tested this, so there might be minor errors. I haven't sorted out exception handling in this code. readLine(), mark() and reset() throw IOException and mark() can also throw IllegalArgumentException