How do i load a text file into this program? - java

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()){..}

Related

Why cant the system find the file that is specified?

in the assignment, the code is suppose to print on a single word from each file that repeats the most. I used a path to get to the list of files used for this assignment and i put them into an array. i cannot seems to find the problem as the array has all the files in it set to string. So why cant it find my file?
below is my code for single thread:
import java.io.*;
import java.util.*;
public class SingleThreaded {
public static void main(String[] args) throws IOException {
File directoryPath = new File("C:\\assignment 3\\links");
String[] dir = directoryPath.list();
System.out.println(Arrays.toString(dir));
String result;
//Scanner scan;
//try{
//Scanner scan = new Scanner(System.in);
long startTime = System.nanoTime();
for (String file : dir) {
//if(file.isFile()){
//BufferedReader inputStream = null;
String line;
//int i;
try{
//inputStream = new BufferedReader(new FileReader(file));file
Scanner scan = new Scanner(new File(file));
HashMap<String, Integer> map = new HashMap<>();
while (scan.hasNextLine()){
line = scan.nextLine().replaceAll("\\p{Punct}", " ");
String[] word = line.split("\s+");
for (int i = 0; i < word.length; i++) {
String string = word[i].toLowerCase();
if (string.length() >= 5) {
if (map.containsKey(string)) {
map.put(string, map.get(string) + 1);
} else {
map.put(string, 1);
}
}
}
}
result = Collections.max(map.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();
System.out.println( file + ": " + result);
}catch (FileNotFoundException e) {
e.printStackTrace();
}
/* }finally{
if(inputStream != null){
inputStream.close();
}
}
*/
// }
}
long endTime = System.nanoTime();
long totalTime = (endTime - startTime)/1000;
System.out.print("Total Time: " + totalTime);
//} catch (FileNotFoundException e) {
//e.printStackTrace();
//}
}
}
I tried changing the path and using different built-in methods but nothing seems to work.
Try this:
public static void main(String[] args) throws IOException {
File directoryPath = new File("C:\\assignment 3\\links");
File[] files = directoryPath.listFiles();
for (File file : files) {
Scanner scan = new Scanner(file);
Notice the difference, using File.listFiles() instead of File.list().

Command Line - FileNotFoundException

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].

CodeEval Challenge Fizz Buzz

I am trying to learn Java. The other day I saw a website providing challenges to solve online. Here is the code project I choose: Fizz Buzz
This is where I am with the project:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.NoSuchElementException;
public class Main {
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
openFile(file);
int[] line = new int[3];
while (nextLine()) {
try{
line = readLine();
String output = getLineOutput(line);
System.out.println(output);
}catch(NoSuchElementException e) { System.out.println("No such element exception"); }
}
}
static Scanner scan;
static void openFile(File file) {
try {
scan = new Scanner((file));
} catch (FileNotFoundException e) {
System.out.println("Could not find file");
}
}
static int[] readLine() {
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
int[] line;
line = new int[] { a, b, c };
return line;
}
static boolean nextLine() {
return scan.hasNextLine();
}
static String getLineOutput(int[] line) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= line[2]; i++)
if (i % line[0] == 0 && i % line[1] == 0) {
sb.append("FB ");
} else {
if (i % line[0] == 0) {
sb.append("F ");
}
if (i % line[1] == 0) {
sb.append("B ");
}
if (i % line[0] > 0 && i % line[1] > 0) {
sb.append(i + " ");
}
}
return sb.toString();
}
}
When I run the program in command prompt providing a path to a text file as the first argument my program seems to work fine. On CodeEval I get the following error:
CodeEval Error: Compilation was aborted after 10 seconds
Should I be accessing the file differently? Is there an exception I'm missing? None of my exceptions are prompting me.
In case this helps anyone in the future this code doesn't close the scanner. Unfortunately on CodeEval the code doesn't execute if this is the case.
Adding scan.close() at the end of main method (after while loop solved) the issue.
Edit: code difference
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
openFile(file);
int[] line = new int[3];
while (nextLine()) {
try{
line = readLine();
String output = getLineOutput(line);
System.out.println(output);
}catch(NoSuchElementException e) { System.out.println("No such element exception"); }
}
scan.close();
}

How to properly display an error when Commandline Argument is left blank by user?

So as you can I see i am reading from a file and displaying all the integers in the file and putting the amount in an array, What I need help with is just a trycatch block which prints out "You did not enter anything", Basically when the Commandline argument is left blank by the user.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class Print5{
public static void main(String[] commandlineArgument) {
Integer[] array = Print5.readFileReturnIntegers(commandlineArgument[0]);
Print5.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] temp = new Integer[10000];
int i = 0;
File file = new File(filename);//Connects File
Scanner inputFile = null;
try{
inputFile = new Scanner(file);
}
catch(FileNotFoundException Exception1) {
System.out.println("File not found!"); //error message when mistyped
}
//where the blank error arg will go
if (inputFile != null) {
try {
while (inputFile.hasNext()) {
try {
temp[i] = inputFile.nextInt();
i++;
} catch (InputMismatchException Exception3) { //change this back to e if doesnt work
inputFile.next();
}
}
}
finally {
inputFile.close();
}
Integer[] array = new Integer[i];
System.arraycopy(temp, 0, array, 0, i);
return array;
}
return new Integer[] {};
}
//Prints the array
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
System.out.println("number of integers in file \"" + filename + "\" = " + array.length);
for (int i = 0; i < array.length; i++) {
System.out.println("index = " + i + "," + " element = " + array[i]);
}
}
}
Add a check on the size of the array and exit the program after displaying an error message:
public static void main(String[] commandlineArgument) {
if(commandlineArgument.length < 1) {
System.err.println("Your error message"); // use the std error stream
System.exit(-1);
}
...
By convention, a nonzero status argument to System.exit() indicates abnormal termination.
Just check the args array length:
public static void main(String[] commandlineArgument) {
if ( commandlineArgument.length > 0 ) {
Integer[] array = Print5.readFileReturnIntegers(commandlineArgument[0]);
Print5.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
else {
System.out.println("usage - ... your message");
}
}
Try using the Apache CLI library.
http://commons.apache.org/proper/commons-cli/
It allows you to define required options and fail out if they're missing.

Scanner will take user input but will not find the file

This is a program to read a file and print out the file with some of the text edited. The code will compile the issue is that it will read the users input but will say file is not found when the file is there. I feel like I am missing something. I am brand new at this so go easy on me.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MainTest {
public static void main(String args[]) {
// if (args[0] != null)
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = "";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count;
} else if (ch == '}') {
out = out + " " + count;
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}
You can use System.getProperty("user.dir") to find where Scanner looking to find your file. And you should be sure your file is located here.

Categories

Resources