ArrayOutofBoundsException - Attempting to read to/from file into Hash Map - java

I'm working on a homework assignment and have run into an odd "ArrayOutOfBoundsException" error - I know what the error means (essentially I'm trying to reference a location in an array that isn't there) but I'm not sure why it's throwing that error? I'm not sure what I'm missing, but obviously there must be some logic error somewhere that I'm not seeing.
PhoneDirectory.java
import java.util.HashMap;
import java.io.*;
class PhoneDirectory {
private HashMap<String, String> directoryMap;
File directory;
public PhoneDirectory() { //create file for phone-directory
directory = new File("phone-directory.txt");
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public PhoneDirectory(String phoneDirectoryFile) {
directory = new File(phoneDirectoryFile);
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public String Lookup(String personName) {
if(directoryMap.containsKey(personName))
return directoryMap.get(personName);
else
return "This person is not in the directory.";
}
public void AddOrChangeEntry(String name, String phoneNumber) {
//ASK IF "IF-ELSE" CHECK IS NECESSARY
if(directoryMap.containsKey(name))
directoryMap.put(name,phoneNumber); //if name is a key, update listing
else
directoryMap.put(name, phoneNumber); //otherwise - create new entry with name
}
public void DeleteEntry(String name) {
if(directoryMap.containsKey(name))
directoryMap.remove(name);
else
System.out.println("The person you are looking for is not in this directory.");
}
public void Write() {
try(BufferedWriter writeDestination = new BufferedWriter(new FileWriter(directory)))
{
for(String key : directoryMap.keySet())
{
writeDestination.write(key + ", " + directoryMap.get(key) + '\n');
writeDestination.newLine();
}
}
catch(IOException err) {
err.printStackTrace();
}
}
}
Driver.java
public class Driver {
PhoneDirectory list1;
public static void main(String[] args) {
PhoneDirectory list1 = new PhoneDirectory("test.txt");
list1.AddOrChangeEntry("Disney World","123-456-7890");
list1.Write();
}
}
Essentially I'm creating a file called "test.txt" and adding the line "Disney World, 123-456-7890" - what's weird is that the code still works - but it throws me that error anyway, so what's really happening? (For the record, I'm referring to the line(s): directoryMap.put(fileData[0], fileData[1]) - which would be line 14 and 28 respectively.)

Related

Add Fileinput to Treemap

I can't add the file input to my map. It says I am missing something and that the Items []is not instantiated. I can't seem to figure it out
public class BigCities {
private Map<String, Set<CityItem>> countryMap;
private File file;
public BigCities(String fileName) {
countryMap = new TreeMap<>();
file = new File(fileName);
readFile(fileName);
}
private void readFile(String fileName) {
// Opg 3c implementeres her.
CityItem cityItem;
try(BufferedReader br = new BufferedReader(new FileReader(fileName))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
String[] items;
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line.split(";");
line = br.readLine();
cityItem = new CityItem(items[1], items[2], items[3]);
}
String everything = sb.toString();
System.out.println(everything);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String toString() {
return countryMap.toString();
}
/**
* #param args
*/
public static void main(String[] args) {
//Vaelg ANSI eller UTF8 afhaengig af hvad der virker bedst paa din computer:
BigCities bc = new BigCities("EuroCities ANSI.txt");
//BigCities bc = new BigCities("EuroCities UTF8.txt");
System.out.println(bc);
}
}
I Don't know what I am missing to add the input, but hopefully someone has some input.
I Am new to programming and therefore I find it confusing, since I feel like I am following all the right methods.
You never initialize the items array, so when trying to access it, you're getting null, or it may just be caught by the compiler and will give you an error there.
I suspect that you mean to assign the split to items, so change the line
line.split(";");
to
items = line.split(";");

read a file and assign key, values java

so I'm trying to make a greedy/jewel heist algorithm in java. I saved the numbers and weights for the jewels to a .txt file. My program is correctly reading the .txt file and I've written a program that can successfully read them. these are the numbers from my .txt file
575 - bag limit
125 3000 (weight, value)
50 100
500 6000
25 30
The problem I'm running into is that I'm struggling to add weights and values to the program. ideally the program would read the tuples and assign them keys and values. I tried to use a hashmap and a regular Map but they haven't been working. possibly because they're in the wrong place. I included both attempted maps and have them commented out like in my program. Would love some help on assigning these values so I can move on to the next step. thanks!!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
// import java.util.HashMap;
// import java.util.Map;
public class readstringastext {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new
BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
String weightLimit = Files.readAllLines(Paths.get("test.txt")).get(0);
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
HashMap<String, String> map = new HashMap<String, String>();
//
// for (String string : pairs) {
// String[] keyValue = string.split(" ");
// map.put(keyValue[0], keyValue[1]);
// System.out.println(keyValue);
// };
//final class MyEntry<K, V> implements Map.Entry<K, V> {
// private final K key;
// private V value;
//
// public MyEntry(K key, V value) {
// this.key = key;
// this.value = value;
// }
// #Override
// public K getKey() {
// return key;
// }
//
// #Override
// public V getValue() {
// return value;
// }
//
// #Override
// public V setValue(V value) {
// V old = this.value;
// this.value = value;
// return old;
// }
// Map.Entry<String, Object> entry = new MyEntry <String, Object>(key, value);
// System.out.println(entry.getKey());
// System.out.println(entry.getValue());
}
}
attempt 2
public class readstringastext {
public static HashMap<String, String> map = new HashMap<String, String>();
public static void weightLimit() {
String weightLimit = "";
System.out.println(weightLimit);
// this is to see if the weightLimit is there which it isnt'.
}
public static void main(String[] args){
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
String weightLimit = "";
boolean first = true;
while ((line = bufferedReader.readLine()) != null) {
if (first) {
weightLimit = line;
first = false;
} else {
String[] values = line.split(" ");
map.put(values[0], values[1]);
}
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I see your code and and I see you read two times the file with Files.readAllLines() and standard method. So I suggest you this solution but you can use Files.readAllLines() too.
public class Main {
public static HashMap<String, String> map = new HashMap<String, String>();
private static String weightLimit = "";
public static void main(String[] args){
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
boolean first = true;
while ((line = bufferedReader.readLine()) != null) {
if (first) {
weightLimit = line;
first = false;
} else {
String[] values = line.split(" ");
map.put(values[0], values[1]);
}
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
weightLimit();
}
public static void weightLimit() {
System.out.println(weightLimit);
}
}
I believe you want to pass in the weight/value pair into a map data structure, I modified your code a little below to enable this:
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
String weightLimit = Files.readAllLines(Paths.get("test.txt")).get(0);
int count = 0;
while ((line = bufferedReader.readLine()) != null) {
if (count != 0) { // ignore the first line
String[] splitValue = line.split(" ");
map.put(splitValue[0], splitValue[1]);
}
count++;
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
// for (Map.Entry<String, String> entry : map.entrySet()) {
// System.out.println(entry.getKey());
// System.out.println(entry.getValue());
// }
}

Compare one Array List object with the next one

Hello guys here my Code
public class Main {
public static List<String> globalList;
public static void main(String[] args) {
globalList = new ArrayList<String>();
File folder = new File("\\Documents\\Folder);
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
for( String t : globalList)
{
System.out.println(t);
}
}
public static void dosomething(File file) {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while ((str = in.readLine()) != null) {
globalList.add(str);
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
In my folder i have a few files. Every file contains a line of information so i took every line and saved the lines to my Arraylist globalList. Now i want to compare one object in my ArrayList with the next one, is this possible?
Just like: if (firstobj == nextobj) remove it.
Edit
Sorry guys i forgot something to write....
The problem is, the line i need to delete arent completly the same, because they start with ah generated number, this number is important for those files so i cant just delete it...
So i need to compare one part of my line if its the same i need to remove it.
One example:
10133;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10134;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX
So now you see the first 2 lines are almost the same except the starting number, i need to find those lines and delete them. Because of changes i cant do somthing like if(list.contains("10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX") ).
In your case if you don't want to check if the part string contains in the list every time then it will take hours if you have a hugefile instead you can use a Set which does not allow duplicates. Unique feature of set is that it does not allow duplicates so instead of taking list of string wrap the string in a custom class and then override the equals and hashcode implementation of the class so that it will not consider the the part of string until the first occurrence of semicolon in the string.
Finally found the working code..
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class MyString
{
public static Set<MyString> globalSet;
private String line;
public String getLine(){
return this.line;
}
public void setLine(String newLine){
this.line = newLine;
}
public static void main(String[] args) {
File folder = new File("C:\\Users\\hbm5cf7\\Documents\\NewF");
globalSet = new HashSet<MyString>();
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
for(MyString t : globalSet)
{
System.out.println(t.getLine());
}
}
public static void dosomething(File file)
{
try {
BufferedReader in = new BufferedReader(new FileReader(file));
MyString str;
String line;
while ((line = in.readLine()) != null) {
str = new MyString();
str.setLine(line);
globalSet.add(str);
}
in.close();
}catch(IOException e)
{
System.out.println(e);
}
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((line == null) ? 0 : line.split(";", 2)[1].hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (getClass() != obj.getClass())
{
return false;
}
if (this.line.equals(((MyString) obj).getLine()))
{
return true;
}
String splitString = ((MyString) obj).getLine().split(";", 2)[1];
if(this.line.endsWith(splitString))
{
return true;
}
return false;
}
}
by overriding the equals and hashcode methods you can decide which one is duplicate and which is not depending upon your requirement
Yes, it's possible. You can use equals method to compare the lines. However, you should rather compare the lines while reading the files and not store the file content in a list and compare. E.g.:
try(BufferedReader reader1 = new BufferedReader(new FileReader(file1));
BufferedReader reader2 = new BufferedReader(new FileReader(file2));){
String line1 = reader1.readLine();
String line2 = reader2.readLine();
if(line1 != null && line1.equals(line2)){
//Do something
}
}catch(Exception e){
//Exception handling
}
I think you're simply trying to ensure that you end up with a single list containing every 'unique' line from every file.
If this is the case you could use an implementation of Set (https://docs.oracle.com/javase/7/docs/api/java/util/Set.html) in place of your globaList such as HashSet https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
The set implementation will ensure that no duplicates are added.
I think you are looking for something like this
Iterator<String> iterator = globalList.iterator();
String lastObj = null;
String nextObj = null;
while (iterator.hasNext()){
nextObj = iterator.next();
if(lastObj == null ){
lastObj = nextObj;
}
else {
if(lastObj.equals(nextObj)){
iterator.remove();
}
}
}
EDIT:
If you have the same generated number followed by an escape character like semicolon you can get the index of the first semicolon and get the substring that start from the next character:
public static void dosomething(File file) {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while ((str = in.readLine()) != null) {
globalList.add(str);
String subString = str.substring(str.indexOf(";") + 1, str.length());
for(Iterator<String> iter = globalList.iterator(); iter.hasNext();)
{
String elem = (String) iter.next();
if(elem.contains(subString))
iter.remove();
}
}
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
Another version:
public static void dosomething(File file) {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while ((str = in.readLine()) != null) {
// remove spaces from beginning and end of the input string
str = str.trim();
String subString = str.substring(str.indexOf(";") + 1, str.length());
boolean match = false;
// search in globalList for a match
for(String elem : globalList)
{
if(elem.contains(subString)){
match = true;
break;
}
}
// if it doesn't contain the string add it
if(!match)
globalList.add(str);
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
#Harish Barma
Files Content:
File1:
2;XXXX;XXXX;;P;XX;XXX;1N410;20170719;1;;;0;0;1;999;1;1;;
10000;1;XXXX 096;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
10001;2;XXXX 097;1410;Autotour 1N410;10;0;K;0;;;0;2;;XXXX
10002;3;XXXX 098;1410;Autotour 1N410;13;0;K;0;;;0;2;;XXXX
10003;4;XXXX 099;1410;Autotour 1N410;19;0;K;0;;;0;2;;XXXX
10004;5;XXXX 100;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
File2:
2;XXXX;XXXX;;P;XX;XXXX;3A680;20170726;1;;;0;0;1;999;1;1;;
10082;1;XXX S146;3680;Autotour 3A680;5;0;K;0;;;0;2;;XXXx
10083;2;XXX S147;3680;Autotour 3A680;8;0;K;0;;;0;2;;XXXX
10084;3;XXX 095;3680;Autotour 3A680;6;0;K;0;;;0;2;3;XXXX
File3:
2;XXXX;XXXX;;P;XX;XXX;4M100;20170719;1;;;0;0;1;999;1;1;;
10129;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10130;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10131;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10132;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10133;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10134;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX
(File 5-100 can cointain same lines like file 3 or different lines like file 1 or 2.)
Code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class MyString
{
public static Set<MyString> globalSet;
private String line;
public String getLine(){
return this.line;
}
public void setLine(String newLine){
this.line = newLine;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (getClass() != obj.getClass())
{
return false;
}
if (this.line.equals(((MyString) obj).getLine())) //compiler said i need to do this so...
{
return true;
}
String splitString = ((MyString) obj).getLine().split(";", 2)[1]; //compiler said i need to do this so...
if(this.line.endsWith(splitString))
{
return true;
}
return false;
}
public static void main(String[] args) {
File folder = new File("C:\\Users\\V90xxxxPCN\\Documents\\Neuer Ordner");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
for(MyString t : globalSet)
{
System.out.println(t.getLine());
}
}
public static void dosomething(File file)
{
try {
globalSet = new HashSet<MyString>();
BufferedReader in = new BufferedReader(new FileReader(file));
MyString str = new MyString();
String line;
while ((line = in.readLine()) != null) {
str.setLine(line);
globalSet.add(str);
}
}catch(IOException e)
{
System.out.println(e);
}
}
}
Expected Output:
2;XXXX;XXXX;;P;XX;XXX;1N410;20170719;1;;;0;0;1;999;1;1;;
10000;1;XXXX 096;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
10001;2;XXXX 097;1410;Autotour 1N410;10;0;K;0;;;0;2;;XXXX
10002;3;XXXX 098;1410;Autotour 1N410;13;0;K;0;;;0;2;;XXXX
10003;4;XXXX 099;1410;Autotour 1N410;19;0;K;0;;;0;2;;XXXX
10004;5;XXXX 100;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
2;XXXX;XXXX;;P;XX;XXXX;3A680;20170726;1;;;0;0;1;999;1;1;;
10082;1;XXX S146;3680;Autotour 3A680;5;0;K;0;;;0;2;;XXXx
10083;2;XXX S147;3680;Autotour 3A680;8;0;K;0;;;0;2;;XXXX
10084;3;XXX 095;3680;Autotour 3A680;6;0;K;0;;;0;2;3;XXXX
2;XXXX;XXXX;;P;XX;XXX;4M100;20170719;1;;;0;0;1;999;1;1;;
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX
Output:
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX

How to use String.split with a text file to add to a simple array

My goal is to read in a text file and add each element to a simple array (the elements are separated by a comma). The last method readData() is the one I can't figure out.
My code so far :
public class VersionChooser {
private Scanner scan;
private StockManager aManager = new StockManager("StockManager");
public VersionChooser() {
this.scan = new Scanner(System.in);
}
public void chooseVersion() {
this.readData();
this.runTextOption();
}
private void runTextOption() {
StockTUI tui = new StockTUI(this.aManager);
}
public StockManager readData() {
String fileName;
System.out.println("Enter the name of the file to be used");
fileName = this.scan.nextLine();
System.out.println(fileName);
try (final BufferedReader br = Files.newBufferedReader(new File("fileName").toPath(),
StandardCharsets.UTF_16)) {
for (String line; (line = br.readLine()) != null;) {
final String[] data = line.split(",");
StockRecord record = new StockRecord(data[0], Double.valueOf(data[4]));
this.aManager.getStockList().add(record);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
StockRecord :
public class StockRecord {
private String date;
private double closingPrice;
public StockRecord(String date, double closingPrice) {
this.date = date;
this.closingPrice = closingPrice;
}
public String getDate() {
return this.date;
}
public double getClosingPrice() {
return this.closingPrice;
}
public String toString() {
return "On " + this.date + " this stock had a closing price of $"
+ this.closingPrice;
}
}
Step1 : Read the file line by line.
Step2: Split the line by ","
Step3 : Construct the String[] to StockRecord.
try (final BufferedReader br = Files.newBufferedReader(new File("stock.txt").toPath(),
StandardCharsets.UTF_8)) {
List<StockRecord> stocks = new ArrayList<StockRecord>();
br.readLine() ; // to avoid first line
for (String line; (line = br.readLine()) != null;) { // first step
final String[] data = line.split(","); // second step
StockRecord record = new StockRecord(data[0], Double.valueOf(data[1]));
stocks.add(record); // third step
}
} catch (IOException e) {
e.printStackTrace();
}
Your stockRecord doesn't has all records. and for demo purpose i did assumed 2 element is closing price . change accordingly

Avoid repetition when writing strings to text file line by line

I use the following code to write strings to my simple text file:
EDITED:
private String fileLocation="/mnt/sdcard/out.txt";
public void saveHisToFile()
{
if (prefs.getBoolean("saveHis", true) && mWordHis != null && mWordHis.size() >= 1)
{
StringBuilder sbHis = new StringBuilder();
Set<String> wordSet= new HashSet<String>(mWordHis);
for (String item : wordSet)
{
sbHis.append(item);
sbHis.append("\n");
}
String strHis = sbHis.substring(0, sbHis.length()-1);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
fileLocation), true));
bw.write(strHis);
bw.newLine();
bw.close();
} catch (IOException e) {
}
}
}
The strings are successfully written to the text file, but weirdly, some strings are overwritten, such as:
apple
orange
grapes
grapes
grapes
apple
kiwi
My question is:
how can I stop a string being written more than once?
how can I stop writing a string (a line) to the file if it has already existed in the file?
I have consulted this post but failed to apply it to my case. Can you please give a little help? Thanks a lot in advance.
Try this:
public void saveHisToFile(Set<String> existingWords)
{
if (prefs.getBoolean("saveHis", true) && mWordHis != null && mWordHis.size() >= 1)
{
StringBuilder sbHis = new StringBuilder();
for (String item : mWordHis)
{
if (!existingWords.contains(item)) {
sbHis.append(item);
sbHis.append("\n");
}
}
String strHis = sbHis.substring(0, sbHis.length()-1);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
fileLocation), true));
bw.write(strHis);
bw.newLine();
bw.close();
} catch (IOException e) {
}
}
}
I guess mWordHis is a List, which can contain duplicate entries.
You can first convert it to a Set (which doesn't allow duplicates) and print only the words in the Set.
Set<String> wordSet= new HashSet<>(mWordHis);
for (String item : wordSet)
{
sbHis.append(item);
sbHis.append("\n");
}
As #fge commented, LinkedHashSet may also be used if insertion order matters.
If you need to run the same code several times with the same file, you must either save in memory all the records you've already wrote to the file, or read the file and get all data before writing to it.
Edit:
I can only think about trimming the words as some may contain unneeded spaces:
Set<String> wordSet= new HashSet<>();
for (String item : mWordHis){
wordSet.add(item.trim());
}
This is a complete example on how to solve your problem:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
public class HisSaver {
private HashSet<String> uniqueTester = new HashSet<String>();
private String fileLocation="/mnt/sdcard/out.txt";
private static HisSaver instance = null;
private HisSaver() {
readWordsFromFile();
}
public static HisSaver getInstance() {
if(instance == null)
instance = new HisSaver();
return instance;
}
public void saveWord(String word) {
if(!uniqueTester.contains(word)) {
uniqueTester.add(word);
writeWordToFile(word);
}
}
private void writeWordToFile(String word) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
fileLocation), true));
bw.write(word);
bw.newLine();
bw.close();
} catch (IOException e) {
}
}
private void readWordsFromFile() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(
fileLocation)));
String line;
while((line = br.readLine()) != null) {
if(!uniqueTester.contains(line)) {
uniqueTester.add(line);
}
}
} catch (IOException e) {
}
}
}
Now to use this, you simply do the following in your code:
HisSaver hs = HisSaver.getInstance();
hs.saveWord("newWord");
This will insert the "newWord" if and only if it is not already in your file, provided that no other function in your code accesses this file. Please note: this solution is NOT thread safe!!!
Edit: Explanation of what the code does:
We create a class HisSaver which is a singleton. This is realized by making it's constructor private and providing a static method getInstance() which returns an initialized HisSaver. This HisSaver will already contain all preexisting words in your file and thus only append new words to it. Calling the getInstance() method from another class will give you a handle for this singleton and allow you to call saveWord without having to worry whether you have the right object in your hands, since only one instance of it can ever be instantiated.
You could add all the strings into a HashMap and check for each new String if it is are already in there.
Example:
HashMap<String,String> test = new HashMap<String,String>();
if(!test.containsKey(item)) {
test.put(item,"");
// your processing: example
System.out.println(item);
} else {
// Your processing of duplicates, example:
System.out.println("Found duplicate of: " + item);
}
Edit: or use a HashSet as shown by the other solutions ...
HashSet<String> test = new HashSet<String>();
if(!test.contains(item)) {
test.add(item);
// your processing: example
System.out.println(item);
} else {
// Your processing of duplicates, example:
System.out.println("Found duplicate of: " + item);
}
Edit2:
private String fileLocation="/mnt/sdcard/out.txt";
public void saveHisToFile()
{
if (prefs.getBoolean("saveHis", true) && mWordHis != null && mWordHis.size() >= 1)
{
StringBuilder sbHis = new StringBuilder();
HashSet<String> test = new HashSet<String>();
Set<String> wordSet= new HashSet<String>(mWordHis);
for (String item : wordSet)
{
if(!test.contains(item)) {
test.add(item);
// your processing: example
sbHis.append(item+System.lineSeparator());
} else {
// Your processing of duplicates, example:
//System.out.println("Found duplicate of: " + item);
}
}
String strHis = sbHis.toString();
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
fileLocation), true));
bw.write(strHis);
bw.newLine();
bw.close();
} catch (IOException e) {
}
}
}

Categories