How to use BufferedReader in a try catch? - java

I've been trying to use bufferedreader several times but every time I get some form error. This is time it is "not a statement" and "; expected" also "catch without try". I keep getting errors at the line with the try(bufferedreader) line. Am I using this correct? I am just trying it out and not quite sure how it works. from the online resource I've been looking at my code looks fine. But when I run my own it gives me errors.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Problem2 {
public static void main(String [] args) {
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(New FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
}
br.close();
}
catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}
}
}

1) The errors are simple, firstly you're supposed to use new FileReader (with lowercase n) rather than New FileReader (with uppercase N).
2) you're closing the else block before attaching the catch handlers to the try block.
I have now corrected both issues and the code below should compile.
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
br.close();
}catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}

Related

reading crossword puzzle txt file

I am new at JAVA and i got no idea how to start this. I was looking for a good start. I need to read a txt file that has a certain format and put it into a view. i first need to read the dimensions of the grid, then the words in the order of the puzzle, then the amount of words needed to be found and last the actual word. If anyone can get me into the right direction with an example, that would really help.
this is the format of the txt file
5 5
abcd
dfad
adfe
lkjl
ekkf
5
realword
realword
realword
realword
realword
EDIT: so this is what i tried after testing to read out the file which works (thanks!). but i get stuk here, i still need to change from char[][] to box[][], since i will be needing it to fill the letterGrid.
import java.io.*;
import java.util.List;
public class Puzzle {
//Box[][] letterGrid;
char[][] letterGrid;
List<Word> wordList;
List<Box> wordInWording;
public Puzzle() {
try {
BufferedReader br = new BufferedReader(new FileReader("..\\word.txt"));
String[] dimensions = br.readLine().split(" ");
letterGrid = new char[Integer.parseInt(dimensions[0])][Integer.parseInt(dimensions[1])];
for (int i = 0; i < letterGrid[0].length; i++) {
String val = br.readLine();
letterGrid[i]= val.toCharArray();
}
//while something something
int r = br.read();
int c = br.read();
letterGrid = new char[r][c];
for (int i = 0; i<r; i++){
String getChar = new String(br.readLine());
for(int j=0; j<c; j++){
letterGrid[i][j] = getChar.charAt(j);
}
}
// String sCurrentLine;
// while ((sCurrentLine = br.readLine()) != null) {
// System.out.println(sCurrentLine);
// }
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is a good Start:
I will just give you hint on how to read lines from a text file. YOu have to build the logic on your own after reading from it.
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
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();
}
}
}
You are not supposed to post such questions in SO without even giving it a try. Try to code, if you get stuck post it then and ask for help. Community does not encourage such questions.

Java: Passing file name and string to the command line

I have a small Java program where I'm trying to pass a text file and one or more strings separated by white spaces at the command line. Inside the text file, I have a list of packages as follows:
gui -> awtui swingui swingui -> runner extensions textui -> runner
framework awtui -> runner runner -> framework extensions -> framework
Now in my java, I want to list each package and its dependencies by passing the text file and package ame at the commandline as follows:
$ java PackageList sample.txt gui swingui
When I press enter, I would like to list each package as follows at the console:
gui -> awtui swingui
swingui -> runner extensions
As you can see, the rest of packages should not appear in the output if they are not passed at the command line as arguments.
Here's my Java code which wish is currently printing all the contents of the file regardless of the command line arguments after file name:
public class PackageList {
public static void main(String[] args) {
File inputFile = null;
if (args.length > 0) {
inputFile = new File(args[0]);
} else {
System.err.println("Invalid arguments count:" + args.length);
System.exit(1);
}
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(inputFile));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Check below code and comments:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class PackageList {
public static void main(String[] args) {
File inputFile = null;
if (args.length > 0) {
inputFile = new File(args[0]);
} else {
System.err.println("Invalid arguments count:" + args.length);
System.exit(1);
}
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(inputFile));
for(int i=1; i < args.length;i++){ // For loop to check - args[0] is file name so i = 1
boolean isDependencyExist = false; // check dependency
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.startsWith(args[i])){ // If file line starts with arg print
System.out.println(sCurrentLine);
isDependencyExist = true;
break;
}
}
if(!isDependencyExist){
System.out.println(args[i] + " ->");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You are reading only args[0] from the command line. You want to read all the other args like this.
After the file has been loaded add
for(int i=1; i<args.length;i++)
{
// read args[i]
}
It better to parse the file content by using Regex or StringTokenizer and put the keys and values into Map.
Then you can lookup the value by the commandline args and print it out.
Pseudocode
Map<String, String> deps = new Hashtable.....;
foreach line of file {
String[] tokens = line.split(" -> ");
deps.put(tokens[0], tokens[1]);
}
for (int i=1; i < args.size(); i++) {
System.out.println(args[i] + " -> " + deps.get(args[i]));
}
Something like that.

Counting number of comments in java

I'm developing a tool to analyse and give some statistics about other people's source code, the tool will be able to recognize many things in the code! Right now am stuck at counting the number of comments on the code, my current code is:
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.startsWith("//")) {
count++;
} else if (line.startsWith("/*")) {
count++;
while (!(line = br.readLine()).endsWith("'*\'")) {
count++;
break;
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
To check the code, I am using a test file. But the code is giving me the wrong result in both files, for example; I am getting three in the following file
Yes
//comment
yes
yes
/*
if
random
test
test
*/
While the answer should be two comments!
In the following file, it's showing me that I have five comments while I still actually have two
Yes
//comment
yes
yes
/*
if
random
test
test
/*
*/
The whole approach is flawed. You need to parse the source file properly, at least you need to keep track properly of quotes and nesting of "/*". Note that any comment character combination can appear inside statements like:
System.out.println("// this is *not* a line comment");
String s = "*/ this is not the end of a block comment";
and so on. Then there is the weird behavior with character escape sequences being processed before the file is interpreted:
\u002F* this is a valid comment */
Its not that easy to determine what is a comment and whats not :) I strongly suggest you look for an open source parser solution for java sources.
I think you have a problem in that comments can occur inside or at the end of a line as well...
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.contains("//")) {
count++;
} else if (line.contains("/*")) {
count++;
while (!line.contains("*/") && !(line = br.readLine()).contains("*/"));
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
Of course the problem here is what if the "//", "/* " or "*/" sequences occur within quoted text....?
I haven't tested your code however, I believe this should work :
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.startsWith("//")) {
count++;
} else if (line.startsWith("/*")) {
count++;
while ((line = br.readLine())!=null && !line.endsWith("'*\'"));
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
When you meet the /* you should increment the counter and skip the comment section.
Guys here is a easy solution. Just download the cloc software from this link for windows.
This software support every language & can accept folder of files also. Put your folder and cloc in same place and open cmd type this command
cloc-(version no).exe (folder name)
cloc-1.64.exe main
and have the no of lines, blank line and total no of lines in the code.
For more detail see this: http://cloc.sourceforge.net/
enter code here
public class FilterInputStreamDemo {
public static void main(String[] args) {
String line = "";
int comment_count = 0;
int line_count = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
line_count++;
if (line.startsWith("//")) {
comment_count++;
single_comment_count++;
} else if (line.startsWith("/*")) {
comment_count++;
multiple_comment_count++;
while (!(line = br.readLine()).endsWith("'*\'")) {
comment_count++;
multiple_comment_count++;
break;
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("comment_count=" + comment_count);
}
}
package com.usaa.training;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CommentsReading {
public static void main(String[] args) {
String line = "";
int number_of_blocks = 0;
int comment_count = 0;
int line_count = 0;
int TODO = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
try {
File file = new File("C:\\code\\InvolvedPartyBasicInfoMapper.java");
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
line_count++;
;
if (line.contains("//")) {
if (line.contains("TODO")){
TODO++;
}
comment_count++;
single_comment_count++;
} else if (line.contains("/*") )
{
if (line.contains("TODO")){
TODO++;
}
comment_count++;
multiple_comment_count++;
if (line.endsWith("*/"))
{
break;
}
while (!(line = br.readLine()).endsWith("'*/'") )
{
line_count++;
comment_count++;
multiple_comment_count++;
if (line.endsWith("*/"))
{
number_of_blocks++;
break;
}
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Total # of Lines = " + line_count);
System.out.println("Total # of Comment Lines= " +comment_count);
System.out.println("Total # of Single line Comments= " +single_comment_count );
System.out.println("Total # of Comment lines with Block Comments = " +multiple_comment_count );
System.out.println("Total # of Block line Comments = " +number_of_blocks);
System.out.println("No of TODO's = " +TODO);
}
}

reading a specific information in file

I want to read this file using Scanner, but not all the information, only the things after semicolon like 10, warrior, John Smith and so on.
currhp: 10
type: Warrior
name: John Smith
items:
Stick,1,2,10,5
gold: 10
type: Wizard
I tried to solve it but i couldn't.
Scanner infile;
Scanner inp = new Scanner(System.in);
try {
infile = new Scanner(new File("player_save.txt"));
} catch (FileNotFoundException o) {
System.out.println(o); return; }
while (infile.hasNextLine()) {
System.out.println(infile.nextLine());
}
You need to open file, read line by line and then split each line and use the chunk of the line that you wish to do further processing on it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile{
public static void main(String[] args) throws IOException {
//fix the URL to where your file is located.
try (BufferedReader br = new BufferedReader(new FileReader("C:\\player_save.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(line.length() > 0) {
if(line.contains(":")) {
System.out.println("Before colon >> " + line.split(":")[0]);
} else {
//no column found taking the whole line
System.out.println("whole line having no coln: " + line);
}
}
}
} catch(FileNotFoundException fnfe) {
//Handle scenario where the file does not exist
} catch(IOException ie) {
//Handle other File I/O exceptions here
}
}
}
You can do something like this -
List<String> list= new ArrayList<>();
try(
Scanner scan= new Scanner(new BufferedReader(new FileReader("//your filepath")));
){
while(scan.hasNextLine()){
String s=scan.nextLine();
if(s.contains(":")){
String arr[]=s.split(":");
list.add(arr[1].trim());
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
for(String str:list){
System.out.println(str);
}

How to print lines from a file that contain a specific word using java?

How to print lines from a file that contain a specific word using java ?
Want to create a simple utility that allows to find a word in a file and prints the complete line in which given word is present.
I have done this much to count the occurence but don't knoe hoe to print the line containing it...
import java.io.*;
public class SearchThe {
public static void main(String args[])
{
try
{
String stringSearch = "System";
BufferedReader bf = new BufferedReader(new FileReader("d:/sh/test.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file...");
while (( line = bf.readLine()) != null)
{
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1)
{
System.out.println("Word is at position " + indexfound + " on line " + linecount);
}
}
bf.close();
}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
Suppose you are reading from a file named file1.txt Then you can use the following code to print all the lines which contains a specific word. And lets say you are searching for the word "foo".
import java.util.*;
import java.io.*;
public class Classname
{
public static void main(String args[])
{
File file =new File("file1.txt");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("foo"))
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
Hope this code helps.
public static void grep(Reader inReader, String searchFor) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(inReader);
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchFor)) {
System.out.println(line);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
Usage:
grep(new FileReader("file.txt"), "GrepMe");
Have a look at BufferedReader or Scanner for reading the file.
To check if a String contains a word use contains from the String-class.
If you show some effort I'm willing to help you out more.
you'll need to do something like this
public void readfile(){
try {
BufferedReader br;
String line;
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("file path"), "UTF-8");
br = new BufferedReader(inputStreamReader);
while ((line = br.readLine()) != null) {
if (line.contains("the thing I'm looking for")) {
//do something
}
//or do this
if(line.matches("some regular expression")){
//do something
}
}
// Done with the file
br.close();
br = null;
}
catch (Exception ex) {
ex.printStackTrace();
}
}

Categories

Resources