Retrieving variables from a text file through a hashmap - java

I am creating a school program for a project in which I a writing words and translations to a file, (separated by a character). I have read that I can read them via a hash map into an array. I was just wondering if someone could point me in the right direction as how to do this.
If anyone has a better idea of how to store and retrieve the words I would love to learn. The reason I am writing to a file is so the user can store as many words as they want.
Thank-you so much :D

You can use java.util.HashMap to store user words and related translations:
String userWord = null;
String translation = null, translation1 = null;
Map<String, String[]> map = new HashMap();
map.put(userWord, new String[] { translation, translation1 });
String[] translations = map.get(userWord);
This map lets you map single userWord to multiple translations.

Here's a reference for learning how to use BufferedReader: BufferedReader
Here's a reference for learning how to use FileReader: FileReader
import java.io.*;
class YourClass
{
public static void main() throws IOException
{
File f = new File("FilePath"); // Replace every '\' with '/' in the file path
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = "";
String FileString = "";
while((line = br.readLine()) != null)
{
// Now 'line' contains each line of the file
// If you want, you can store the entire file in a String, like this:
FileString += line + "\n"; // '\n' to register each new line
}
System.out.println(FileString);
}
} // End of class
I'm still a newbie, and don't understand much about HashMap, but I can tell you how to store it in a String array:
FileString = FileString.replaceAll("\\s+", " ");
String[] Words = FileString.split(" ");
FileString.replaceAll("\\s+", " ") - Replaces 1 or more spaces with 1 space, so as to avoid any logical errors.
FileString.split(" ") - Returns a String array of each String separated by a space.

You can try something like this
File f = new File("/Desktop/Codes/Text.txt");
// enter your file location
HashMap<String, String[]> hs = new HashMap<String, String[]>();
// throw exception in main method
Scanner sc = new Scanner(f);
String s="";
while(sc.hasNext()){
s = sc.next();
// create a method to search translation
String []trans = searchTrans(s);
hs.put(s, trans);
}

Related

Trying to separate a txt file into two ArrayLists?

This image is a text file I need to separate by date and the digits alongside it
BufferedReader wordReader = new BufferedReader(new FileReader("\\Users\\rosha\\eclipse-workspace\\working\\src\\workingfix\\spx_data_five_years.txt"));
ArrayList<String> spxIndex = new ArrayList<>();
ArrayList<String> date = new ArrayList<>();
//populating the Array with the file
String line = wordReader.readLine();
while (line != null) {
date.add(line);
line = wordReader.readLine();
}
wordReader.close();
Would really love to understand how to separate this file into two Arrays. Been at it for a while and some Guidance in the right direction would be incredible. Apologies if it's a simple solution for some reason I'm having trouble getting started.
Here is the some of the Text File, if I can get guidance on this I'll be in good shape
1/4/2010 1132.99
1/5/2010 1136.52
1/6/2010 1137.14
1/7/2010 1141.69
1/8/2010 1144.98
1/11/2010 1146.98
1/12/2010 1136.22
1/13/2010 1145.68
Your two examples are a little bit different, in the Image, it seems like the entries are separated by a tab. In your text example, the entries are separated by a space. If they are separated by a space, a simple String[] splitter = line.split(" "); suffices. This gives you the result as an Array, which you can write in the ArrayLists.
Here is the solution, using split method
public static void main(String[] args) throws IOException {
ArrayList<String> spxIndex = new ArrayList<>();
ArrayList<String> date = new ArrayList<>();
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader("\\Users\\rosha\\eclipse-workspace\\working\\src\\workingfix\\spx_data_five_years.txt"));
while ((sCurrentLine = br.readLine()) != null) {
String[] lineValues = sCurrentLine.split(" ");
date.add(lineValues[0]);
spxIndex.add(lineValues[1]);
}
br.close();
System.out.println(date);
System.out.println(spxIndex);
}

Inputting string read from a .txt file into an array

I am making a flashcard like app for my high school software project. I am able to store words and their respective translation by writing them to a file, but I was wondering if there was a possible way to read them into a 2d array.
Could I separate them with commas, or some other character?
Additionally would there be a way to link the words and their respective translations. For example if I called word 'x', is there a function to call word 'translated x' if it is in an array?
Thanks heaps!!
You might want to look at Maps. That way you could look up each word by the word itself rather than iterating through an Array. Maps use Key Value pairs. Unfortunately, they are unidirctional (you can't look up a key by it's value).
https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
Let's break down the problem a bit.
read the file
parse each line in the file to determine a word and a translation
store the word and the translation in a data structure (#Glen Pierce's suggestion about using a map is a good one)
Let's say our file looks like this, we use a comma to delimit the word and the translation (this is also the extent of my Spanish vocabulary):
hello,hola
good,bueno
Now some code, let's read the file into a map.
// a map of word to translation
Map<String, String> wordMap = new HashMap<String, String>();
// a class that can read a file (we wrap the file reader in a buffered reader because it's more efficient to read a file in chunks larger than a single character)
BufferedReader fileReader = new BufferedReader(new FileReader("my-file.txt"));
// a line from the file
String line;
// read lines until we read a line that is null (i.e. no more lines)
while((line = fileReader.getLine()) != null) {
// split the line, returns an array of parts
String[] parts = line.split(",");
// store the parts in meaningful variables
String word = parts[0];
String translation = parts[1];
// now, store the word and the translation in the word map
wordMap.put(word, translation);
}
// close the reader (note: you should do this with a try/finally block so that if you throw an exception, you still close the reader)
fileReader.close();
So now we have a map that has all the words and translations in the file. Given a word, you can retrieve the translation like this:
String word = "hello";
String translation = wordMap.get(word);
System.out.println(word + " translates to " + translation);
Output:
hello translates to hola
I guess the next step is to have the user give you a word and for you to return the correct translation. I'll leave that to you.
Do you need to store the words in a text file (i.e., do they need to persist), or can you store them in memory?
If they need to be written to a text file, try this:
// Create a file
File file = new File("file.txt");
// Initialize a print writer to print to the file
PrintWriter pw = new PrintWriter(file);
Scanner keyboard = new Scanner(System.in);
// Populate
boolean stop = false;
do {
String word;
String translation;
System.out.print("Enter a word: ");
word = keyboard.nextLine().trim() + " ";
if (!word.equals("quit ")) {
pw.print(word);
System.out.print("Enter its translation: ");
translation = keyboard.nextLine().trim();
pw.println(translation);
} else {
stop = true;
}
} while (!stop);
// Close the print writer and write to the file
pw.close();
// Initialize a scanner to read the file
Scanner fileReader = new Scanner(file);
// Initialize a hash table to store the values from the file
Hashtable<String, String> words = new Hashtable<String, String>();
// Add the information from the file to the hash table
while (fileReader.hasNextLine()) {
String line = fileReader.nextLine();
String[] array = line.split(" ");
words.put(array[0], array[1]);
}
// Print the results
System.out.println("Results: ");
words.forEach((k, v) -> System.out.println(k + " " + v));
fileReader.close();
keyboard.close();
Note that I am using a space to separate the word from its translation. You can just as easily use a comma or a semicolon or what have you. Just replace line.split(" ") with line.split(< your separating character here>) and concatenate it to the end of word = keyboard.nextLine().trim().
If you don't need to save the information and just need to collect the user's input, it's even simpler:
Scanner keyboard = new Scanner(System.in);
// Initialize a hash table to store the values from the user
Hashtable<String, String> words = new Hashtable<String, String>();
// Get the input from the user
boolean stop = false;
do {
String word;
String translation;
System.out.print("Enter a word: ");
word = keyboard.nextLine().trim();
if (!word.equals("quit")) {
System.out.print("Enter its translation: ");
translation = keyboard.nextLine().trim();
words.put(word, translation);
} else {
stop = true;
}
} while (!stop);
// Print the results
System.out.println("Results: ");
words.forEach((k, v) -> System.out.println(k + " " + v));
keyboard.close();

How CSV parsing can be utilized - JAVA

I am given a file that will read the following:
"String",int,int
"String",int,int
"String",int,int
...
Given an unknown number of variables, a while (scanner.hasNextLine()) can solve to the number of entries. My goal is to take these three pieces of data and store them into a Node. I am using the method BinaryTree.addNode(String, int, int) for this. My issue comes to when I am trying to read in the data. I am trying to remove the commas within the document and then attempting to re-read the data using the following:
Scanner firstpass = new Scanner(file);
String input = firstpass.nextLine().replaceAll(",", "");
Scanner secondpass = new Scanner(input);
String variable1 = secondpass.next();
int variable2 = secondpass.nextInt();
int variable3 = secondpass.nextInt();
This however is a very innefective way of going about this.
UPDATED
The compiling errors can be fixed with the following:
try {
Scanner scanner1 = new Scanner(file);
while (scanner1.hasNextLine()) {
String inventory = scanner1.nextLine().replaceAll(",", " ");
Scanner scanner2 = new Scanner(inventory);
while (scanner2.hasNext()){
String i = scanner2.next();
System.out.print(i);
}
scanner2.close();
}
scanner1.close();
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
which gives me the output:
"String"intint"String"intint"String"intint...
So I know I am on the right track. However any (spaces) within the "String" variable are removed. So they would output "SomeString" instead of "Some String". Also I still don't know how to remove the "" from the strings.
The format you've shown matches the CSV (Comma-Separated Values) format, so your best option is to use a CSV parser, e.g. Apache Commons CSV ™.
If you don't want to add a third-party library, you could use Regular Expression to parse the line.
Reading lines from a file should not be done with a Scanner. Use a BufferedReader instead. See Scanner vs. BufferedReader.
try (BufferedReader in = new BufferedReader(new FileReader(file))) {
Pattern p = Pattern.compile("\"(.*?)\",(-?\\d+),(-?\\d+)");
for (String line; (line = in.readLine()) != null; ) {
Matcher m = p.matcher(line);
if (! m.matches())
throw new IOException("Invalid line: " + line);
String value1 = m.group(1);
int value2 = Integer.parseInt(m.group(2));
int value3 = Integer.parseInt(m.group(3));
// use values here
}
} catch (IOException | NumberFormatException ex) {
ex.printStackTrace();
}
Note that this will not work if the string contains escaped characters, e.g. if it contains embedded double-quotes. For that, you should use a parser library.
The code above will correctly handle embedded spaces and commas.
I would instead of using
String input = firstpass.nextLine().replaceAll(",", "");
Scanner secondpass = new Scanner(input);
String variable1 = secondpass.next();
int variable2 = secondpass.nextInt();
int variable3 = secondpass.nextInt();
Use the following approach
String line = firstpass.nextLine();
String[] temp = line.split(",");
String variable1 = temp[0];
int variable2 = Integer.parseInt(temp[1]);
int variable3 = Integer.parseInt(temp[2]);

Scanning, spliting and assigning values from a text file

I'm having trouble scanning a given file for certain words and assigning them to variables, so far I've chosen to use Scanner over BufferedReader because It's more familiar. I'm given a text file and this particular part I'm trying to read the first two words of each line (potentially unlimited lines) and maybe add them to an array of sorts. This is what I have:
File file = new File("example.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] ary = line.split(",");
I know It' a fair distance off, however I'm new to coding and cannot get past this wall...
An example input would be...
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
...
and the proposed output
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
...
You can try something like this
File file = new File("D:\\test.txt");
Scanner sc = new Scanner(file);
List<String> list =new ArrayList<>();
int i=0;
while (sc.hasNextLine()) {
list.add(sc.nextLine().split(",",2)[0]);
i++;
}
char point='A';
for(String str:list){
System.out.println("Variable"+point+" = "+str);
point++;
}
My input:
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
Out put:
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
To rephrase, you are looking to read the first 2 words of a line (everything before the first comma) and store it in a variable to process further.
To do so, your current code looks fine, however, when you grab the line's data, use the substring function in conjunction with indexOf to just get the first part of the String before the comma. After that, you can do whatever processing you want to do with it.
In your current code, ary[0] should give you the first 2 words.
public static void main(String[] args)
{
File file = new File("example.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
List l = new ArrayList();
while ((line = br.readLine()) != null) {
System.out.println(line);
line = line.trim(); // remove unwanted characters at the end of line
String[] arr = line.split(",");
String[] ary = arr[0].split(" ");
String firstTwoWords[] = new String[2];
firstTwoWords[0] = ary[0];
firstTwoWords[1] = ary[1];
l.add(firstTwoWords);
}
Iterator it = l.iterator();
while (it.hasNext()) {
String firstTwoWords[] = (String[]) it.next();
System.out.println(firstTwoWords[0] + " " + firstTwoWords[1]);
}
}

How to read a String (file) to array in java

Suppose there is a file named as SUN.txt
File contains : a,b,dd,ss,
I want to make dynamic array depending upon the number of attributes in file.
If ther is a char after comma then array will be of 0-4 i.e of length 5.
In the above mentioned case there is no Char which returns 0-3 Array of length 4. I want to read the NULL after comma too.
How do i do that?
Sundhas
You should think about
Reading the file into a String
Splitting the file by separator ','
Using a list for adding the characters and convert the list to an array, when the list is filled
As Markus said, you want to do something like this..
//Create a buffred reader so that you can read in the file
BufferedReader reader = new BufferedReader(new FileReader(new File(
"\\SUN.txt")));
//The StringBuffer will be used to create a string if your file has multiple lines
StringBuffer sb = new StringBuffer();
String line;
while((line = reader.readLine())!= null)
{
sb.append(line);
}
//We now split the line on the "," to get a string array of the values
String [] store = sb.toString().split(",");
I do not quite understand why you would want the NULL after the comma? I am assuming that you mean after the last comma you would like that to be null in your array? I do not quite see the point in that but that is not what the question is.
If that is the case you wont read in a NULL, if after the comma there was a space, you could read that in.
If you would like a NULL you would have to add it in yourself at the end so you could do something like
//Create a buffred reader so that you can read in the file
BufferedReader reader = new BufferedReader(new FileReader(new File(
"\\SUN.txt")));
//Use an arraylist to store the values including nulls
ArrayList<String> store = new ArrayList<String>();
String line;
while((line = reader.readLine())!= null)
{
String [] splitLine = line.split(",");
for(String x : splitLine)
{
store.add(line);
}
//This tests to see if the last character of the line is , and will add a null into the array list
if(line.endsWith(","))
store.add(null);
}
String [] storeWithNull = store.toArray();
Well if you want want to simply open the file and store the content in a array of string then
1) open the file into a string
2) split the string using a regex "," http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)
but I'm curious why you can't use a String file directly ?
For your datatructure, use a list of arrays. Each list entry is a line of your textfile, each entry is an array that holds the comma separated values:
List<String[]> data = new ArrayList<String[]>();
String line = readNextLine(); // custom method, to be implemented
while (line != null) {
data.add(line.split(","));
line = readNextLine();
}
(assuming, your file contains 1..n lines of comma separated values)
You may want to have it like this:
"a,b,c,d," -> {"a", "b", "c", "d", null}
Here's a suggestion how to solve that problem:
List<String[]> data = new ArrayList<String[]>();
String line = readNextLine(); // custom method, to be implemented
while (line != null) {
String[] values = new String[5];
String[] pieces = line.split(",");
for (int i = 0; i<pieces.length; i++)
values[i] = pieces[i];
data.add(values);
line = readNextLine();
}
its seems like a CSV file something like this will work assuming it has 5 lines and 5 values
String [][] value = new String [5][5];
File file = new File("SUN.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
int row = 0;
int col = 0;
while((line = br.readLine()) != null ){
StringTokenizer s = new StringTokenizer(line,",");
while (s.hasMoreTokens()){
value[row][col] = s.nextToken();
col++;
}
col = 0;
row++;
}
i havent tested this code
Read the file, using BufferedReader, one line at the time.
Use split(",", -1) to convert to an array of String[] including also empty strings beyond the last comma as part of your array.
Load the String[] parts into a List.

Categories