Command Line - FileNotFoundException - java

I am working on creating a tester.
When I tried
javac WordListsTester.java
java WordListsTester a.txt
I think it should show an error message as the file has to be "dictionary.txt" but, it does not.
What should I fix?
public class WordListsTester {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
WordLists scrabble = new WordLists("dictionary.txt");
String[] containLetter = scrabble.containsLetter(3, 'a');
output(containLetter, "containsLetter.txt");
String[] wordsStarts = scrabble.startsWith(3, 'a');
output(wordsStarts, "startsWith.txt");
String[] wordLength = scrabble.lengthN(3);
output(wordLength, "lengthN.txt");
String[] multiLetter = scrabble.multiLetter(2, 'h');
output(multiLetter, "multiLetter.txt");
String[] vowelHeavy = scrabble.vowelHeavy(5, 2);
output(vowelHeavy, "vowelHeavy.txt");
input.close();
}
public static void output(String[] words, String fileName) {
try {
PrintWriter out = new PrintWriter(fileName);
if (words.length == 0) {
System.out.println("NO matched Words exist");
}
for (int i = 0; i < words.length; i++) {
out.println(words[i]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Invalid file name.");
}
}
}

WordLists scrabble = new WordLists(args[0]);
Not sure what this program does exactly.
Not sure if file name is being checked inside the WordLists class.
But if you want to check USER INPUT, you need to check args[0].

Related

How to sort a cvs file by one field in Java?

How can I sort a cvs file by one field in Java?
For example I want to sort it by the third field
I have a cvs file that looks like this:
1951,Jones,5
1984,Smith,7
...
I tried using Scanner as such, with a delimiter but I couldn't figure out how to go on:
public static void main(String[] args)
{
//String data = args[0];
Scanner s = null;
String delim = ";";
try
{
s = new Scanner(new BufferedReader (new FileReader("test.csv")));
List<Integer> three = new ArrayList<Integer>();
while(s.hasNext())
{
System.out.println(s.next());
s.useDelimiter(delim);
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
finally
{
if(s != null)
{
s.close();
}
}
}
Thank you!
public static void main(String[] args)
{
final String DELIM = ";";
final int COLUMN_TO_SORT = 2; //First column = 0; Third column = 2.
List<List<String>> records = new ArrayList<>();
try (Scanner scanner = new Scanner(new File("test.csv"))) {
while (scanner.hasNextLine()) {
records.add(getRecordFromLine(scanner.nextLine(), DELIM));
}
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
Collections.sort(records, new Comparator<List<String>>(){
#Override
public int compare(List<String> row1, List<String> row2){
if(row1.size() > COLUMN_TO_SORT && row2.size() > COLUMN_TO_SORT)
return row1.get(COLUMN_TO_SORT).compareTo(row2.get(COLUMN_TO_SORT));
return 0;
}
});
for (Iterator<List<String>> iterator = records.iterator(); iterator.hasNext(); ) {
System.out.println(iterator.next());
}
}
private static List<String> getRecordFromLine(String row, String delimiter) {
List<String> values = new ArrayList<String>();
try (Scanner rowScanner = new Scanner(row)) {
rowScanner.useDelimiter(delimiter);
while (rowScanner.hasNext()) {
values.add(rowScanner.next());
}
}
return values;
}
** Note that the example file is separated by comma, but in the code you use semicolon as the delimiter.

I'm getting FileNotFound exception while trying to create a file

I'm trying to prompt the user to input the name a file they'd like to write to, create that .txt file and then write the qualifying lines of text into that file and save it. inside the do while, it seems to be skipping over the user input for the name of the file they'd like to save to, looping back around and then getting a FileNotFoundException, and it shouldn't even be looking for a file.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you
would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
do {
System.out.println("please enter a name for the file to write to
(end with .txt): ");
String out = user.nextLine(); //PROBLEM HERE! SKIPS USER INPUT
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0],
Integer.parseInt(elements[1]),
Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]),
Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost &&
bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I just needed to skip a line before the loop began.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
user.nextLine(); //SOLUTION HERE
do {
System.out.println("please enter a name for the file to write to (end with .txt): ");
String out = user.nextLine();
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0], Integer.parseInt(elements[1]), Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]), Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost && bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}

How do i load a text file into this program?

How do i go about loading a text file into a java program that i have posted below. I have tried but am out of luck, any help will be appreciated!
Thank you.
import java.io.*;
public class test1 {
public static void main(String args[]) throws Exception {
if (args.length != 1) {
System.out.println("usage: Tut16_ReadText filename");
System.exit(0);
}
try {
FileReader infile = new FileReader(args[0]);
BufferedReader inbuf = new BufferedReader(infile);
String str;
int totalwords = 0, totalchar = 0;
while ((str = inbuf.readLine()) != null) {
String words[] = str.split(" ");
totalwords += words.length;
for (int j = 0; j < words.length; j++) {
totalchar += words[j].length();
}
}
double density = (1.0 * totalchar) / totalwords;
if (totalchar > 0) {
System.out.print(args[0] + " : " + density + " : ");
if (density > 6.0)
System.out.println("heavy");
else
System.out.println("light");
} else
System.out.println("This is an error - denisty of zero.");
infile.close();
} catch (Exception ee) {
System.out.println("This is an error - execution caught.");
}
}
}
If you are running java 8 it is a breeze with the new io streams. Advantage is on large file all text is not read into memory.
public void ReadFile(String filePath){
File txtFile = new File(filePath);
if (txtFile.exists()) {
System.out.println("reading file");
try (Stream<String> filtered = Files.
lines(txtFile.toPath()).
filter(s -> s.contains("2006]"))) {//you can leave this out, but is handy to do some pre filtering
filtered.forEach(s -> handleLine(s));
}
} else {
System.out.println("file not found");
}
}
private void handleLine(String lineText) {
System.out.println(lineText);
}
First of all, there is an easier way to read files. From Java 7 the Files and Paths classes can be used like this:
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("usage: Tut16_ReadText filename");
System.exit(0);
}
final List<String> lines = Files.readAllLines(Paths.get(args[0]));
for (String line : lines) {
// Do stuff...
}
// More stuff
}
Then, in order to start the program and get it to read a file that you specify you must provide an argument when starting the app. You pass that argument after the class name on the command prompt like this:
$ java Tut16_ReadText /some/path/someFile.txt
This passes "/some/path/someFile.txt" to the program and then the program will try to read that file.
Another method is to use a Scanner.
Scanner s = new Scanner(new File(args[0]));
while(s.hasNext()){..}

Command Line Returning Blank

After entering file to be processed the command line jumps to next line but remains blank, as opposed to printing the desired array. I want to call the getInputScanner() method to produce the scanner that accesses the file, after the file is entered by the user the command line jumps to the next line, as opposed to processing any of the text. Any ideas why?
import java.util.*;
import java.awt.*;
import java.io.*;
public class Test {
public static void main(String [] args) {
Scanner console = new Scanner(System.in);
Scanner input = getInputScanner(console);
System.out.println("{" + nameArr(input) + "}");
}
public static Scanner getInputScanner(Scanner console) {
System.out.print("Please enter a file to process: ");
File file = new File(console.next());
while (!file.exists()) {
System.out.print("\nFile does not exists.\nPlease enter a new file name: ");
file = new File(console.next());
}
try {
Scanner fileScanner = new Scanner(file);
return fileScanner;
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
return null;
}
public static String [] nameArr(Scanner input) {
int count = 0;
while (input.hasNextLine()) {
count++;
}
String [] nameArray = new String[count];
while (input.hasNextLine()) {
String line = input.nextLine();
for (int i = 0; i < nameArray.length; i++) {
nameArray[i] = lineProcess(input.nextLine());
}
}
return nameArray;
}
public static String lineProcess(String line) {
Scanner lineScan = new Scanner(line);
String line2 = lineScan.nextLine();
String lineString[] = line2.split(" ");
String name = lineString[0];
return name;
}
}
You've and infinite loop since you're not advancing the scanner calling input.nextLine():
while (input.hasNextLine()) {
count++;
}
I see other parts of the code which I'm thing that are wrong, try using java.util.List instead of array to collect the names in the lines of your processed file:
import java.util.*;
import java.io.*;
public class Test {
public static void main(String [] args) {
Scanner console = new Scanner(System.in);
Scanner input = getInputScanner(console);
List<String> nameList = nameArr(input);
for(String name : nameList){
System.out.println("{ "+ name + " } ");
}
}
public static Scanner getInputScanner(Scanner console) {
System.out.print("Please enter a file to process: ");
File file = new File(console.next());
while (!file.exists()) {
System.out.print("\nFile does not exists.\nPlease enter a new file name: ");
file = new File(console.next());
}
try {
Scanner fileScanner = new Scanner(file);
return fileScanner;
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
return null;
}
public static List<String> nameArr(Scanner input) {
List<String> nameList = new ArrayList<String>();
while (input.hasNextLine()) {
nameList.add(lineProcess(input.nextLine()));
}
return nameList;
}
public static String lineProcess(String line) {
return line.split(" ")[0];
}
}

Error: java.util.NoSuchElementException - Scanner not behaving as desired

Scanner returning NoSuch Element Exception error. Could you explain why is this happening.
The Scanner now passes and runs fine but it didn't take the nextLine input from the second Scanner call. This may be a little tweak but could someone point out what the mistake is.
public class JavaHW1_1 {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) throws IOException {
String pattern ;
String fileName = null;
// Method to manage user inputs
fileName = userInputFileName(userInput);
pattern = userInputPattern(userInput);
// To find the pattern in the file
// findPattern();
}
private static String userInputPattern(Scanner userInput) {
String pattern = "JollyGood";
System.out.println(". Please enter a pattern to find in the file");
while(userInput.hasNextLine()){
pattern = userInput.nextLine();
System.out.println("The pattern to be searched: "+ pattern);
}
userInput.close();
return pattern;
}
private static String userInputFileName(Scanner userInput) throws IOException {
String path = "./src";
String files, fileName;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
System.out.println("Please input the desired file name:\n");
System.out.println("Some suggestions:\n");
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().endsWith(".txt"))
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}
int userAttempt = 0;
do{
fileName = userInput.nextLine();
if(fileName.toLowerCase().endsWith(".txt")){
System.out.println("The file name entered is in correct format");
File file = new File("./src",fileName);
try {
file.createNewFile();
System.out.println("File is created. Please enter text to be written in the file. End the content with \"eof\"");
InputOutput(file.getName());
} catch (IOException e) {
e.printStackTrace();
}
userAttempt = 10;
}
else
{System.out.println("Please enter correct format file with .txt extension");
userAttempt++;}
}while (userAttempt <10);
return fileName;
}
private static void InputOutput(String fName) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("./src/" + fName));
String inputLine = null;
do {
inputLine=in.readLine();
out.write(inputLine);
out.newLine();
} while (!inputLine.equalsIgnoreCase("aaa"));
System.out.print("Write Successful");
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}
private static void findPattern() {
// TODO Auto-generated method stub
}
}
Based in this SO, you might be closing the Scanner and creating a new one to read from the System.in and it makes sense by looking at your code.
So my suggestion for you code is to receive the Scanner by parameter, something like this:
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
String pattern = userInputPattern(scan);
String test = readSomethingElse(scan);
}
private static String readSomethingElse(Scanner scan) {
System.out.println(". Read something else");
return scan.nextLine();
}
private static String userInputPattern(Scanner scan) {
String pattern = "JollyGood";
System.out.println(". Please enter a pattern to find in the file");
pattern = scan.nextLine();
System.out.println("The pattern to be searched: "+ pattern);
return pattern;
}
It could happen if you pass EOF straight into the standard input. For example (in windows):
java com.myprog.MainClass
^Z
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
....
The ^Z above represents a Ctrl-Z on windows command prompt which is an EOF signal
You need to consider your requirement and process / display error if user is provided a EOF without any prior data

Categories

Resources