Identifying each word in a file - java

Importing a large list of words and I need to create code that will recognize each word in the file. I am using a delimiter to recognize the separation from each word but I am receiving a suppressed error stating that the value of linenumber and delimiter are not used. What do I need to do to get the program to read this file and to separate each word within that file?
public class ASCIIPrime {
public final static String LOC = "C:\\english1.txt";
#SuppressWarnings("null")
public static void main(String[] args) throws IOException {
//import list of words
#SuppressWarnings("resource")
BufferedReader File = new BufferedReader(new FileReader(LOC));
//Create a temporary ArrayList to store data
ArrayList<String> temp = new ArrayList<String>();
//Find number of lines in txt file
String line;
while ((line = File.readLine()) != null)
{
temp.add(line);
}
//Identify each word in file
int lineNumber = 0;
lineNumber++;
String delimiter = "\t";
//assess each character in the word to determine the ascii value
int total = 0;
for (int i=0; i < ((String) line).length(); i++)
{
char c = ((String) line).charAt(i);
total += c;
}
System.out.println ("The total value of " + line + " is " + total);
}
}

This smells like homework, but alright.
Importing a large list of words and I need to create code that will recognize each word in the file. What do I need to do to get the program to read this file and to separate each word within that file?
You need to...
Read the file
Separate the words from what you've read in
... I don't know what you want to do with them after that. I'll just dump them into a big list.
The contents of my main method would be...
BufferedReader File = new BufferedReader(new FileReader(LOC));//LOC is defined as class variable
//Create an ArrayList to store the words
List<String> words = new ArrayList<String>();
String line;
String delimiter = "\t";
while ((line = File.readLine()) != null)//read the file
{
String[] wordsInLine = line.split(delimiter);//separate the words
//delimiter could be a regex here, gotta watch out for that
for(int i=0, isize = wordsInLine.length(); i < isize; i++){
words.add(wordsInLine[i]);//put them in a list
}
}

You can use the split method of the String class
String[] split(String regex)
This will return an array of strings that you can handle directly of transform in to any other collection you might need.
I suggest also to remove the suppresswarning unless you are sure what you are doing. In most cases is better to remove the cause of the warning than supress the warning.

I used this great tutorial from thenewboston when I started off reading files: https://www.youtube.com/watch?v=3RNYUKxAgmw
This video seems perfect for you. It covers how to save file words of data. And just add the string data to the ArrayList. Here's what your code should look like:
import java.io.*;
import java.util.*;
public class ReadFile {
static Scanner x;
static ArrayList<String> temp = new ArrayList<String>();
public static void main(String args[]){
openFile();
readFile();
closeFile();
}
public static void openFile(){
try(
x = new Scanner(new File("yourtextfile.txt");
}catch(Exception e){
System.out.println(e);
}
}
public static void readFile(){
while(x.hasNext()){
temp.add(x.next());
}
}
public void closeFile(){
x.close();
}
}
One thing that is nice with using the java util scanner is that is automatically skips the spaces between words making it easy to use and identify words.

Related

Java- Reversing Text in a document

I am trying to write a program that will read a file, copy it, and reverse the text- meaning the last word in the document is now the first. The method I created does not reverse when moved to the output file.
public static ArrayList<String> fileLines(String filename) throws FileNotFoundException {
ArrayList<String> lines = new ArrayList<String>();
Scanner fileRead = new Scanner(new File(filename));
while (fileRead.hasNextLine()) {
String line = fileRead.nextLine();
lines.add(line);
}
fileRead.close();
return lines;
}
public static void writeLinesReverse(ArrayList<String> lines, String filename) throws FileNotFoundException {
PrintWriter fileWrite = new PrintWriter(new File(filename));
for (int i = lines.size() - 1; i > -1; i--) {
fileWrite.write(lines.get(i));
}
fileWrite.close();
}
}
Why dont you use Collections.reverse to reverse the arraylist
Maybe something like this
//reverse list
Collections.reverse(lines);
for (String s: lines) {
//write to file
}
Docs
// Reverse the complete line
while (fileRead.hasNextLine()) {
String line = fileRead.nextLine();
lines.add(new StringBuffer(line).reverse().toString());
}
input: Stack overflow
output: wolfrevo kcatS
If you want to reverse the content of word in each line,
1) First read the line
2) Use split() function to get individual words in the line
3) Create StringBuffer on each word and reverse it as shown above.
If you follow this approach,
output will be
kcatS wolfrevo

Read a text file to an array Java

I know there are many questions about reading text files here but I have gone through all of them and I think I'm having some difficulty with syntax or SOMETHING because nothing that I've been trying has been working at all.
What I'm attempting to do is this:
1) read a text file inputed by user
2) copy each individual line into an array, so each line is its own element in the array
I feel like I am very close but for some reason I can't figure out exactly how to get it to work!
Here is the relevant code I have right now:
I keep getting out of bounds exceptions in three locations which I've marked off.
Been working on this for quite a while not sure what to do next! Any ideas?
import java.io.IOException;
import java.util.Scanner;
public class FindWords {
public static void main (String args[]) throws IOException{
FindWords d = new Dictionary();
((Dictionary) d).dictionary(); //********* out of bounds here
}
/**
* Validates and returns the dictionary inputed by the user.
*
* #param
* #return the location of the dictionary
*/
public static String getDict(){
///////////////////ASK FOR DICTIONARY////////////////////
System.out.println("Please input your dictionary file");
//initiate input scanner
Scanner in = new Scanner(System.in);
// input by user
String dictionary = in.nextLine();
System.out.println("Sys.print: " + dictionary);
//make sure there is a dictionary file
if (dictionary.length() == 0){
throw new IllegalArgumentException("You must enter a dictionary");
}
else return dictionary;
}
}
which calls on the class Dictionary:
import java.io.*;
public class Dictionary extends FindWords{
public void dictionary () throws IOException{
String dict = getDict();
String[] a = readFile(dict); //********** out of bounds here
int i = 0;
while(a[i] != null){
System.out.println(a[i]);
i++;
}
}
public static String[] readFile(String input) throws IOException{
//read file
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
System.out.println ();
int count = 0;
String[] array = new String[count];
try{
while (br.readLine() != null){
array[count] = br.readLine(); //********out of bounds here
count++;
}
br.close();
}
catch (IOException e){
}
return array;
}
}
Thank you for looking!
Edit: Just fyi: I have my .txt file in the parent project folder.
Have you tried this?:
List<String> lines = Files.readAllLines(Paths.get("/path/to/my/file.txt"));
and then transform your list to an array if you want:
String[] myLines = lines.toArray(new String[lines.size()]);
You start with an array size of zero...
int count = 0;
String[] array = new String[count];
Several issues here :
In Java, you can't expand arrays, i.e you have to know their length in advance when you instantiate them. Hence the ArrayOutOfBoundException. To make this easy, I suggest that you use an ArrayList instead.
In your while loop, you're making 2 calls to br.readLine(), so basically you're skipping one line out of 2.
You are initializing a zero-length array, hence the exception on the first iteration:
int count = 0;
String[] array = new String[count];
Since you probably don't know the expected size, work with a List instead:
List<String> list = new ArrayList<>();
String thisLine = null;
try{
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
}
You can get the total size afterwards by:
list.size();
Or even better, go with morganos solution and use Files.readAllLines().

How to store words from a file into a string, and print them out in reverse?

So I need to do exactly what it says in the title, take a text file called "words.txt", have the program read it, take all the words in it, and store them into an array. After that, the program needs to pick one out randomly, and print it in reverse. I'm having a lot of trouble getting it to work, as it always crashes at the end. Here's what I got so far:
import java.io.*;
import java.util.Random;
public class wordReader{
public static void main (String args[]) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
String strLine;
String[] filearray;
filearray = new String[10];
while ((strLine = br.hasNextLine())) {
for (int j = 0; j < filearray.length; j++){
filearray[j] = br.readLine();
System.out.println(filearray);
}
}
}
}
Alright, this i what I have at the moment:
import java.io.*;
import java.util.Random;
public class wordReader{
public static void main (String args[]) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
String strLine;
String[] filearray;
filearray = new String[10];
int j = 0;
int i = 0;
Random r = new Random();
while(((strLine = br.readLine()) !=null) && j < filearray.length){
filearray[j++] = strLine;
int idx = r.nextInt(filearray.length);
}
}
}
You can do this easily using the new Files API and StringBuilder to reverse your String. It will cut down your lines of code significantly.
public static void main(String[] args) throws Exception {
Path path = Paths.get("words.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
String[] words = content.split(",|\.|\s+");
int randomIndex = new Random().nextInt(words.length);
String word = words[randomIndex];
String reversed = StringBuilder(word).reverse().toString();
System.out.println(reversed);
}
Try using the StringTokenizer to read the line.
http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Lot's of ways to accomplish this. Here's a recursive method that prints as the calls are popping off the return stack. This was adapted from Reversing Lines With Recursion Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
public class ReverseLines {
public static BufferedReader input;
public static PrintWriter output;
public static void main(String[] args) throws Exception {
input = new BufferedReader(new FileReader("/tmp/words.txt"));
output = new PrintWriter(System.out);
reverse(input, output);
input.close();
output.flush();
output.close();
}
public static void reverse(BufferedReader input, PrintWriter output)
throws Exception {
String line = input.readLine();
if (line != null) {
reverse(input, output);
output.println(line);
}
}
}
You don't seem to have gotten to the point of doing the random index selection or the line reversal yet, so I won't address that stuff here. There are endless duplicates all over StackOverflow to tell you how to reverse a String.
At the moment, you're getting compile errors because (among other things) you're trying to use a method (BufferedReader#hasNextLine()) that doesn't exist. It looks like you were mixing up a couple of other approaches that you might have found, e.g.:
int j = 0;
while ((strLine = br.readLine()) != null) { // Set strLine to the next line
filearray[j++] = strLine; // Add strLine to the array
// I don't recommend printing the whole array on every pass through the loop...
}
You'll notice that I also took out your inner for loop, because it was just setting every element of your list to the most recent line on every iteration. I'm assuming you wanted to populate the list with all of your lines. Realistically, you should also check whether j is in an acceptable range as well:
while (((strLine = br.readLine()) != null) && j < filearray.length) {...}
Note that realistically, you'd almost certainly be better off using a List to store your lines, so you could just add all the lines to the List and not worry about the length:
List<String> contents = new ArrayList<String>();
while ((strLine = br.readLine()) != null) {
contents.add(strLine); // Add strLine to the List
}
But, this does smell like homework, so maybe you're required to use a String[] for whatever reason.
Finally, there's a discrepancy between what you've written in your question and what your program looks like it's intended to do. You claim that you need a list of each word, but it looks more like you're trying to create a list of each line. If you need words instead of lines, you'll need to split up each line and add each token to the list.

Need help creating an array that reads and writes a .txt and lists words in alphabetical orders

I just started to code a while back and I'm in the process of dealing with arrays on my own, I understand them in theory but I need some help when it comes to getting practical. I asked my instructor to give me a couple of practices problems and he gave me the following.
using this as your main:
public static void main(String[] args) {
DatosPalabras datos = new DatosPalabras( "words.txt" );
JOptionPane.showMessageDialog(null, datos );
datos.sort();
JOptionPane.showMessageDialog(null, datos);
}
(its in spanish so bear with me) create a class named DatosPalabras and words.txt and make sure your code can:
Read and display words.txt
Display the words in "words.txt" in alphabetical order
I really appreciate the help, I'm a bit stumped but I'm curious to know how I can accomplish this. Thank you!
EDIT:
public class DatosPalabras {
public DatosPalabras(String string) {
// read and display the content of words.txt
}
public void sort() {
// need info on what to use in order to sort words instead of doubles and integers.
}
}
In this example I have 1 file named Q19505617.java. Java only allows you to have 1 public class per file. It is the class that defines the main method. So this example works only because the DatosPalabras class is contained in that file. If you need DatosPalabras to be its own class then put the DatosPalabras in its own file named DatosPalabras.java and change the class signature to be public class DatosPalabras.
import java.io.InputStream;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Q19505617 {
public static void main(String[] args) {
DatosPalabras datos = new DatosPalabras("words.txt");
JOptionPane.showMessageDialog(null, datos);
datos.sort();
JOptionPane.showMessageDialog(null, datos);
}
}
class DatosPalabras {
private String[] lines;
public DatosPalabras(String filename) {
lines = new String[1];
int lineCounter = 0;
InputStream in = Q19505617.class.getResourceAsStream(filename);
Scanner scanner = new Scanner(in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
if(lineCounter == lines.length) {
lines = Arrays.copyOf(lines, lines.length * 2);
}
lines[lineCounter] = line;
lineCounter++;
}
}
public void sort() {
// put your real sort algorithm here. until then use this:
}
public String toString() {
StringBuilder b = new StringBuilder();
for (String line : lines) {
b.append(line).append("\n");
}
return b.toString();
}
}
You can create a reading Array like this:
String[] Array = new String[number of lines in you txt file];
int i = 0;
// Selecting the txt file
File theFile = new File("bla.txt");
//Creating a scanner to read the file
scan = new Scanner(theFile);
//Reading all the words from the txt file
while (scan.hasNextLine()) {
line = scan.nextLine();
Array[i] = line; // gets all the lines
i++;
Then you create a method for sorting.

reading from text file to string array

So I can search for a string in my text file, however, I wanted to sort data within this ArrayList and implement an algorithm. Is it possible to read from a text file and the values [Strings] within the text file be stored in a String[] Array.
Also is it possible to separate the Strings? So instead of my Array having:
[Alice was beginning to get very tired of sitting by her sister on the, bank, and of having nothing to do:]
is it possible to an array as:
["Alice", "was" "beginning" "to" "get"...]
.
public static void main(String[]args) throws IOException
{
Scanner scan = new Scanner(System.in);
String stringSearch = scan.nextLine();
BufferedReader reader = new BufferedReader(new FileReader("File1.txt"));
List<String> words = new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
for(String sLine : words)
{
if (sLine.contains(stringSearch))
{
int index = words.indexOf(sLine);
System.out.println("Got a match at line " + index);
}
}
//Collections.sort(words);
//for (String str: words)
// System.out.println(str);
int size = words.size();
System.out.println("There are " + size + " Lines of text in this text file.");
reader.close();
System.out.println(words);
}
To split a line into an array of words, use this:
String words = sentence.split("[^\\w']+");
The regex [^\w'] means "not a word char or an apostrophe"
This will capture words with embedded apostrophes like "can't" and skip over all punctuation.
Edit:
A comment has raised the edge case of parsing a quoted word such as 'this' as this.
Here's the solution for that - you have to first remove wrapping quotes:
String[] words = input.replaceAll("(^|\\s)'([\\w']+)'(\\s|$)", "$1$2$3").split("[^\\w']+");
Here's some test code with edge and corner cases:
public static void main(String[] args) throws Exception {
String input = "'I', ie \"me\", can't extract 'can't' or 'can't'";
String[] words = input.replaceAll("(^|[^\\w'])'([\\w']+)'([^\\w']|$)", "$1$2$3").split("[^\\w']+");
System.out.println(Arrays.toString(words));
}
Output:
[I, ie, me, can't, extract, can't, or, can't]
Also is it possible to separate the Strings?
Yes, You can split string by using this for white spaces.
String[] strSplit;
String str = "This is test for split";
strSplit = str.split("[\\s,;!?\"]+");
See String API
Moreover you can also read a text file word by word.
Scanner scan = null;
try {
scan = new Scanner(new BufferedReader(new FileReader("Your File Path")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(scan.hasNext()){
System.out.println( scan.next() );
}
See Scanner API

Categories