I am trying to create an implementation that reads a file that the user has typed and submitted. The code for that is located in the SetTester class (shown below). In my implementation I already have an array declared called String[] myArray = new String [] {}; to hold the data from the file. How would I be able to take the file that is being called in the tester class and put it into that array?
public class SetTester
{
public static void main(String [] args) {
StringSet words = new MyStringSet();
Scanner file = null;
FileInputStream fs = null;
String input;
Scanner kb = new Scanner(System.in);
int wordCt = 0;
boolean ok = false;
while (!ok)
{
System.out.print("Enter name of input file: ");
input = kb.nextLine();
try
{
fs = new FileInputStream(input);
ok = true;
}
catch (FileNotFoundException e)
{
System.out.println(input + " is not a valid file. Try again.");
}
}
file = new Scanner(fs);
while (file.hasNext())
{
input = file.next();
words.insert(input);
System.out.println("Current capacity: " + words.getCapacity());
wordCt++;
}
System.out.println("There were " + wordCt + " words in the file");
System.out.println("There are " + words.inventory() + " elements in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
while (!words.contains(input))
{
System.out.println(input + " is not in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
}
words.remove(input);
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("The first 10 words in the set are: ");
for (int x=0; x<10; x++)
System.out.println(words.getFirstItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("5 random words from the set are: ");
for (int x=0; x<5; x++)
System.out.println(words.getRandomItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
}
}
For reading from a file I use this class:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private static String path;
public ReadFile(String file_path){
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for (int j = 0; j < numberOfLines; j++) {
textData[j] = textReader.readLine();
}
textReader.close();
return textData;
}
static int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
then in the class main you can add this code and you edit the path so you can read a file an get an array out of it
public static void main(String args[]) throws IOException {
ReadFile r = new ReadFile("here you put the path that the user provide");
String[] text = r.OpenFile();
ArrayList<String> array = new ArrayList<>();
array.addAll(Arrays.asList(text));
}
If you have any questions let me know!
Related
I am doing a class project that is supposed to read a .txt file and have the program also replace some text. But after I run the code it just constantly runs in a loop and only reading one line of the text. Not really sure what I did wrong but I think it's the reader part of my code.
public class FormLetter
{
final static int MAX_LINES = 20;
final static int NUM_INSERTIONS = 4;
String[] formLetter = new String[MAX_LINES];
int lines = 0;
public static void main(String[] args)
{
FormLetter letter1 = new FormLetter("formLetter..txt");
FormLetter letter2 = new FormLetter("longLetter.txt");
FormLetter letter3 = new FormLetter("formLetter.txt");
letter3.generateLetter("insertions.txt");
}
public FormLetter(String formFileName)
{
Scanner formFileIn;
String line;
Path file = Paths.get("H:\\Eclipse\\Programming Project 1\\formLetter.txt");
InputStream input = null;
try
{
formFileIn = new Scanner(new FileReader(formFileName));
while (lines < MAX_LINES && formFileIn.hasNextLine())
{
input = Files.newInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
Charset.defaultCharset();
line = reader.readLine();
System.out.println(line);
}
if (formFileIn.hasNextLine())
{
System.out.println("File " + formFileName + " is too large to process.\n");
}
}
catch(FileNotFoundException fnfe)
{
System.out.println("Cannot open " + formFileName + "\n");
}
catch(IOException ioe)
{
System.out.println("Error reading from file" + formFileName);
}
}
As mentioned in the comments I was using two readers by mistake causing an infinite loop. I removed the second reader and during my loop now only put to output the next line from the file.
import java.util.Scanner;
import java.io.*;
import java.nio.file.*;
import java.nio.charset.*;
import java.nio.file.StandardOpenOption;
public class FormLetter
{
final static int MAX_LINES = 20;
final static int NUM_INSERTIONS = 4;
String[] formLetter = new String[MAX_LINES];
int lines = 0;
public static void main(String[] args)
{
FormLetter letter1 = new FormLetter("formLetter..txt");
FormLetter letter2 = new FormLetter("longLetter.txt");
FormLetter letter3 = new FormLetter("formLetter.txt");
letter3.generateLetter("insertions.txt");
}
public FormLetter(String formFileName)
{
Scanner formFileIn;
String line;
try
{
formFileIn = new Scanner(new FileReader("H:\\Eclipse\\Programming Project 1\\formLetter.txt"));
while (lines < MAX_LINES && formFileIn.hasNextLine())
{
System.out.println(formFileIn.next());
}
if (formFileIn.hasNextLine())
{
System.out.println("File " + formFileName + " is too large to process.\n");
}
}
catch(FileNotFoundException fnfe)
{
System.out.println("Cannot open " + formFileName + "\n");
}
catch(IOException ioe)
{
System.out.println("Error reading from file" + formFileName);
}
}
The program I am coding allows the user to find a matching credit card number in three text files. However, it outputs that no matches have been found in any of the comparisons between the files. If someone could guide me on how to fix this problem, that would be great! Down below is the code for the program.
Edit: it seems that I forgot to place the number 1000 in some of the comparisons between the files. I now have a null exception problem at
if(numbers1[i].compareTo(numbers2[i]) == 0){
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MatchingNumber {
public static int counter = 0;
public static int flag;
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
static BufferedReader in3 = new BufferedReader(new InputStreamReader(System.in));
static int x;
static String[] numbers1 = new String[1000];
static String[] numbers2 = new String[1000];
static String[] numbers3 = new String[1000];
public static void main(String[] args) throws IOException {
loadNumbers();
firstCompare();
secondCompare();
thirdCompare();
}
public static void loadNumbers() throws IOException {
String findFile, file;
//ask for location of file
System.out.println("Enter File 1 Location: ");
//Read input
findFile = in.readLine();
//find file
file = findFile + "/creditCards1.txt";
BufferedReader in = new BufferedReader(new FileReader(file));
String findFile1, file1;
//ask for location of file
System.out.println("Enter File 2 Location: ");
//Read input
findFile1 = in2.readLine();
//find file
file1 = findFile1 + "/creditCards2.txt";
BufferedReader in2 = new BufferedReader(new FileReader(file1));
String findFile2,file2;
//ask for location of file
System.out.println("Enter File 3 Location: ");
//Read input
findFile2 = in3.readLine();
//find file
file2 = findFile2 + "/creditCards3.txt";
BufferedReader in3 = new BufferedReader(new FileReader(file2));
for (int i = 0; i < 1000; i++){
//read in the data
numbers1[i] = in.readLine();
numbers2[i] = in2.readLine();
numbers3[i] = in3.readLine();
counter++;
}
in.close();
in2.close();
in3.close();
}
public static void firstCompare() {
boolean found = false;
for (int i = 0; i < 1000; i++){
if(numbers1[i].compareTo(numbers2[i]) == 0){
flag = i;
found = true;
System.out.println(flag + "is the matching number in files 1 and 2");
}
}
if (!found){
System.out.println("No matches found files 1 and 2");
}
}
public static void secondCompare() {
boolean found = false;
for (int i = 0; i < 1000; i++){
if(numbers1[i].compareTo(numbers3[i]) == 0){
flag = i;
found = true;
System.out.println(flag + "is the matching number in files 1 and 3");
}
}
if (!found){
System.out.println("No matches found files 1 and 3");
}
}
public static void thirdCompare() {
boolean found = false;
for (int i = 0; i < 1000; i++){
if(numbers2[i].compareTo(numbers3[i]) == 0){
flag = i;
found = true;
System.out.println(flag + "is the matching number in files 2 and 3");
}
}
if (!found){
System.out.println("No matches found files 2 and 3");
}
}
}
First of all, why do you limit your amount of credit card numbers?
static String[] numbers1 = new String[1000];
static String[] numbers2 = new String[1000];
static String[] numbers3 = new String[1000];
I would recommend using:
static List<String> numbers1 = new List<String>();
static List<String> numbers2 = new List<String>();
static List<String> numbers3 = new List<String>();
This will allow you to increase your project's scalability and reduce redundancy when comparing.
When comparing, you can simply loop through one list and check if another list contains the element that you are looking for:
boolean found = false;
int i = 0;
while(!found)
{
if(numbers1.Contains(numbers2[i])
found = true;
i++;
}
I am working on a program which imports a library from a generated file.
The file generates properly and is found by Scanner. The first line has a single int as written by
pw.println(cdarchive.getNumber());
Elsewhere in the code. This part seems to work fine.
This is the error I'm getting:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at no.hib.dat102.IO.readFile(IO.java:26)
at no.hib.dat102.Menu.start(Menu.java:34)
at no.hib.dat102.CdArchiveClient.main(CdArchiveClient.java:10)
The line it refers to is
int libSize = in.nextInt();
This is my method:
public class IO {
static final String DELIMITER = "#";
public static CdArchiveADT readFile(String filename) {
Scanner in = null;
CdArchiveADT cda = null;
try
{
File f = new File(filename+".txt");
in = new Scanner(f);
System.out.println(f);
in.useDelimiter(DELIMITER);
int libSize = in.nextInt();
System.out.println("libSize" + libSize);
cda = new CdArchive(libSize);
for (int i=0; i<libSize;i++) {
int inId = in.nextInt();
String inTitle= in.next();
String inArtist = in.next();
String inLabel = in.next();
String inGenre = in.next();
int inYear = in.nextInt();
in.nextLine();
cda.addCd(new CD(inId, inArtist, inTitle, inYear, inGenre, inLabel));
System.out.println("Closing Scanner (input)");
in.close();
}
}
catch (FileNotFoundException e){
System.out.println("Config file not found!");
e.printStackTrace();
}
return cda;
}
EDIT:
This is the method that writes to the file:
public static void writeFile(CdArchiveADT cdarchive, String filename) throws IOException {
PrintWriter pw = null;
File file = null;
try {
file = new File(filename +".txt");
// Create the file if it does not already exist
file.createNewFile();
// Writing metadata
pw = new PrintWriter(new FileWriter(file, false));
pw.println(cdarchive.getNumber());
// Writing data, if CdArchive is not empty
if (cdarchive.getCdTable()[0] != null) {
for (int i = 0; i<cdarchive.getNumber(); i++ ) {
CD c = cdarchive.getCdTable()[i];
pw.print(c.getId()); pw.print(DELIMITER);
pw.print(c.getTitle()); pw.print(DELIMITER);
pw.print(c.getArtist()); pw.print(DELIMITER);
pw.print(c.getLabel()); pw.print(DELIMITER);
pw.print(c.getGenre()); pw.print(DELIMITER);
pw.print(c.getYear()); pw.println(DELIMITER);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
e.printStackTrace();
}
finally
{
if ( pw != null )
{
System.out.println("Closing PrintWriter");
pw.close();
}
}
}
I got a working example:
public static void main(String[] args) {
// write
String delimiter = "#";
StringWriter stringWriter = new StringWriter();
PrintWriter pw = new PrintWriter(stringWriter);
pw.println(3);
for (int i = 0; i < 3; i++) {
pw.print("id " + i);
pw.print(delimiter);
pw.print("titel " + i);
pw.print(delimiter);
pw.print("artist " + i);
pw.println(delimiter);
}
String theString = stringWriter.toString();
System.out.println(theString);
try {
pw.close();
stringWriter.close();
} catch (IOException e) {
// ignore in example
}
// read
Scanner in = new Scanner(theString);
in.useDelimiter("\\s*#\\s*|\\s*\n\\s*"); // add new line as delimiter aswell
int libSize = in.nextInt();
for (int i = 0; i < libSize; i++) {
String inId = in.next();
String inTitle = in.next();
String inArtist = in.next();
in.nextLine();
System.out.println("read: " + inId + ", " + inTitle + ", " + inArtist);
}
in.close();
}
The point is to add new line to the used delimiters aswell
try to use
static final String DELIMITER = "\\s*#\\s*";
Otherwise any leading or trailing spaces will cause that error.
Background: This program reads in a text file and replaces a word in the file with user input.
Problem: I am trying to read in a line of text from a text file and store the words into an array.
Right now the array size is hard-coded with an number of indexes for test purposes, but I want to make the array capable of reading in a text file of any size instead.
Here is my code.
public class FTR {
public static Scanner input = new Scanner(System.in);
public static Scanner input2 = new Scanner(System.in);
public static String fileName = "C:\\Users\\...";
public static String userInput, userInput2;
public static StringTokenizer line;
public static String array_of_words[] = new String[19]; //hard-coded
/* main */
public static void main(String[] args) {
readFile(fileName);
wordSearch(fileName);
replace(fileName);
}//main
/*
* method: readFile
*/
public static void readFile(String fileName) {
try {
FileReader file = new FileReader(fileName);
BufferedReader read = new BufferedReader(file);
String line_of_text = read.readLine();
while (line_of_text != null) {
System.out.println(line_of_text);
line_of_text = read.readLine();
}
} catch (Exception e) {
System.out.println("Unable to read file: " + fileName);
System.exit(0);
}
System.out.println("**************************************************");
}
/*
* method: wordSearch
*/
public static void wordSearch(String fileName) {
int amount = 0;
System.out.println("What word do you want to find?");
userInput = input.nextLine();
try {
FileReader file = new FileReader(fileName);
BufferedReader read = new BufferedReader(file);
String line_of_text = read.readLine();
while (line_of_text != null) { //there is a line to read
System.out.println(line_of_text);
line = new StringTokenizer(line_of_text); //tokenize the line into words
while (line.hasMoreTokens()) { //check if line has more words
String word = line.nextToken(); //get the word
if (userInput.equalsIgnoreCase(word)) {
amount += 1; //count the word
}
}
line_of_text = read.readLine(); //read the next line
}
} catch (Exception e) {
System.out.println("Unable to read file: " + fileName);
System.exit(0);
}
if (amount == 0) { //if userInput was not found in the file
System.out.println("'" + userInput + "'" + " was not found.");
System.exit(0);
}
System.out.println("Search for word: " + userInput);
System.out.println("Found: " + amount);
}//wordSearch
/*
* method: replace
*/
public static void replace(String fileName) {
int amount = 0;
int i = 0;
System.out.println("What word do you want to replace?");
userInput2 = input2.nextLine();
System.out.println("Replace all " + "'" + userInput2 + "'" + " with " + "'" + userInput + "'");
try {
FileReader file = new FileReader(fileName);
BufferedReader read = new BufferedReader(file);
String line_of_text = read.readLine();
while (line_of_text != null) { //there is a line to read
line = new StringTokenizer(line_of_text); //tokenize the line into words
while (line.hasMoreTokens()) { //check if line has more words
String word = line.nextToken(); //get the word
if (userInput2.equalsIgnoreCase(word)) {
amount += 1; //count the word
word = userInput;
}
array_of_words[i] = word; //add word to index in array
System.out.println("WORD: " + word + " was stored in array[" + i + "]");
i++; //increment array index
}
//THIS IS WHERE THE PRINTING HAPPENS
System.out.println("ARRAY ELEMENTS: " + Arrays.toString(array_of_words));
line_of_text = read.readLine(); //read the next line
}
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter("C:\\Users\\..."));
for (i = 0; i < array_of_words.length; i++) { //go through the array
outputWriter.write(array_of_words[i] + " "); //write word from array to file
}
outputWriter.flush();
outputWriter.close();
} catch (Exception e) {
System.out.println("Unable to read file: " + fileName);
System.exit(0);
}
if (amount == 0) { //if userInput was not found in the file
System.out.println("'" + userInput2 + "'" + " was not found.");
System.exit(0);
}
}//replace
}//FTR
You can use java.util.ArrayList (which dynamically grows unlike an array with fixed size) to store the string objects (test file lines) by replacing your array with the below code:
public static List<String> array_of_words = new java.util.ArrayList<>();
You need to use add(string) to add a line (string) and get(index) to retrieve the line (string)
Please refer the below link for more details:
http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
You may want to give a try to ArrayList.
In Java normal arrays cannot be initialized without giving initial size and they cannot be expanded during run time. Whereas ArrayLists have resizable-array implementation of the List interface.ArrayList also comes with number of useful builtin functions such as
Size()
isEmpty()
contains()
clone()
and others. On top of these you can always convert your ArrayList to simple array using ArrayList function toArray(). Hope this answers your question. I'll prepare some code and share with you to further explain things you can achieve using List interface.
Use not native [] arrays but any kind of java collections
List<String> fileContent = Files.readAllLines(Paths.get(fileName));
fileContent.stream().forEach(System.out::println);
long amount = fileContent.stream()
.flatMap(line -> Arrays.stream(line.split(" +")))
.filter(word -> word.equalsIgnoreCase(userInput))
.count();
List<String> words = fileContent.stream()
.flatMap(line -> Arrays.stream(line.split(" +")))
.filter(word -> word.length() > 0)
.map(word -> word.equalsIgnoreCase(userInput) ? userInput2 : word)
.collect(Collectors.toList());
Files.write(Paths.get(fileName), String.join(" ", words).getBytes());
of course you can works with such lists more traditionally, with loops
for(String line: fileContent) {
...
}
or even
for (int i = 0; i < fileContent.size(); ++i) {
String line = fileContent.get(i);
...
}
i just like streams :)
I am writing code that reads in a text file through the command line arguments in the main method and prints out each word in it on its own line without printing any word more than once, it will not print anything, can anyone help?
import java.util.*;
import java.io.*;
public class Tokenization {
public static void main(String[] args) throws Exception{
String x = "";
String y = "";
File file = new File(args[0]);
Scanner s = new Scanner(file);
String [] words = null;
while (s.hasNext()){
x = s.nextLine();
}
words = x.split("\\p{Punct}");
String [] moreWords = null;
for (int i = 0; i < words.length;i++){
y = y + " " + words[i];
}
moreWords = y.split("\\s+");
String [] unique = unique(moreWords);
for (int i = 0;i<unique.length;i++){
System.out.println(unique[i]);
}
s.close();
}
public static String[] unique (String [] s) {
String [] uniques = new String[s.length];
for (int i = 0; i < s.length;i++){
for(int j = i + 1; j < s.length;j++){
if (!s[i].equalsIgnoreCase(s[j])){
uniques[i] = s[i];
}
}
}
return uniques;
}
}
You have several problems:
you're reading whole file line by line, but assign only last line to variable x
you're doing 2 splits, both on regexp, it is enough 1
in unique - you're filling only some parts of array, other parts are null
Here is shorter version of what you need:
import java.io.File;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Tokenization {
public static void main(String[] args) throws Exception {
Set<String> words = new HashSet<String>();
try {
File file = new File(args[0]);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String[] lineWords = scanner.nextLine().split("[\\p{Punct}\\s]+");
for (String s : lineWords)
words.add(s.toLowerCase());
}
scanner.close();
} catch (Exception e) {
System.out.println("Cannot read file [" + e.getMessage() + "]");
System.exit(1);
}
for (String s : words)
System.out.println(s);
}
}