Java: Passing file name and string to the command line - java

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.

Related

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();
}
}

Can not print out a set in Java

i am writing a program that read in two text files and find the differences
but for some reason, i can not print the result set. I checked for lot of times and still couldn't find the reason and i hope you guys can help me out. here is the code.
the problem occur at the for each to print the set.
import java.io.*;
import java.util.*;
public class PartOne {
public static void readFileAtPath(String filePathOne, String filePathTwo) {
// Lets make sure the file path is not empty or null
if (filePathOne == null || filePathOne.isEmpty()) {
System.out.println("Invalid File Path");
return;
}
if (filePathTwo == null || filePathTwo.isEmpty()) {
System.out.println("Invalid File Path");
return;
}
Set<String> newUser = new HashSet<String>();
Set<String> oldUser = new HashSet<String>();
BufferedReader inputStream = null;
BufferedReader inputStream2 = null;
// We need a try catch block so we can handle any potential IO errors
try {
// Try block so we can use ‘finally’ and close BufferedReader
try {
inputStream = new BufferedReader(new FileReader(filePathOne));
inputStream2 = new BufferedReader(new FileReader(filePathTwo));
String lineContent = null;
String lineContent2 = null;
// Loop will iterate over each line within the file.
// It will stop when no new lines are found.
while ((lineContent = inputStream.readLine()) != null) {
// Here we have the content of each line.
// For now, I will print the content of the line.
// System.out.println("Found the line: " + lineContent);
oldUser.add(lineContent);
}
while ((lineContent2 = inputStream.readLine()) != null) {
newUser.add(lineContent2);
}
Set<String> uniqueUsers = new HashSet<String>(newUser);
uniqueUsers.removeAll(oldUser);
}
// Make sure we close the buffered reader.
finally {
if (inputStream != null)
inputStream.close();
if (inputStream2 != null)
inputStream2.close();
}
for (String temp : uniqueUsers) {
System.out.println(temp);
}
} catch (IOException e) {
e.printStackTrace();
}
}// end of method
public static void main(String[] args) {
String filePath2 = "userListNew.txt";
String filePath = "userListOld.txt";
readFileAtPath(filePath, filePath2);
}
}
Your problem is scope. You define the set inside your try block but then you attempt to access it from outside that block. You must define all variables within the same scope you want to use that variable.
Move the definition of uniqueUsers to before your try block.
*Edit in response to your comment.
You are reading from the same input stream twice. The second while loop should be reading from inputStream2.
Try this
try {
// Try block so we can use ‘finally’ and close BufferedReader
try {
inputStream = new BufferedReader(new FileReader(filePathOne));
inputStream2 = new BufferedReader(new FileReader(filePathTwo));
String lineContent = null;
String lineContent2 = null;
// Loop will iterate over each line within the file.
// It will stop when no new lines are found.
while ((lineContent = inputStream.readLine()) != null) {
// Here we have the content of each line.
// For now, I will print the content of the line.
// System.out.println("Found the line: " + lineContent);
oldUser.add(lineContent);
}
while ((lineContent2 = inputStream.readLine()) != null) {
newUser.add(lineContent2);
}
Set<String> uniqueUsers = new HashSet<String>(newUser);
uniqueUsers.removeAll(oldUser);
for (String temp : uniqueUsers) {
System.out.println(temp);
}
}
// Make sure we close the buffered reader.
finally {
if (inputStream != null)
inputStream.close();
if (inputStream2 != null)
inputStream2.close();
}
} catch (IOException e) {
e.printStackTrace();
}

converting lines of imported text file to arrays and printing arrays to make graph in Netbeans and Swing

I want to import any .txt files (note the .txt files will have a 3 sets of numbers in one column; separating each set with a space)
2
3
4
3
2
1
1
2
3
and convert the set of numbers into arrays. (array 1 , 2 and 3)
array1[] = {2,3,4}
array2[] = {3,2,1}
array3[] = {1,2,3}
then be able to graph the array in JFreeGraph Library
here's how i started...i'm using netbeans and java Swing
#Action
public void openMenuItem() {
int returnVal = jFileChooser1.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = jFileChooser1.getSelectedFile();
try {
FileReader fileReader = new FileReader(file);
jTextArea2.read(new FileReader(file.getAbsolutePath()), null);
} catch (IOException ex) {
System.out.println("problem accessing file" + file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}
Read from a file line by line, perhaps using BufferedReader and readLine. Once you encounter an empty line - you have a new set of numbers. Here is an oversimplified example that maintains a list of lists, and reads only strings:
public static List<List<String>> parseFile(String fileName){
BufferedReader bufferedReader = null;
List<List<String>> lists = new ArrayList<List<String>>();
List<String> currentList = new ArrayList<String>();
lists.add(currentList);
try {
bufferedReader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if (line.isEmpty()){
currentList = new ArrayList<String>();
lists.add(currentList);
} else {
currentList.add(line);
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return lists;
}
EDIT: using resulting lists with JTextArea
List<List<String>> lists = parseFile("test.txt");
for (List<String> strings : lists){
textArea.append(StringUtils.join(strings, ",") + "\n");
System.out.println(StringUtils.join(strings, ","));
}

Categories

Resources