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) {
}
}
}
Related
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(";");
I am trying to open a csv file using openCSV, iterate over every column and if the userID is different write a new JavaBean pair at the end of the file.
The problem is that the reader only checks the first column of my file and not the whole file. While created, the file contains only a header and nothing else. The program will check every column and if the sudoID is different it will write it to the file. If the sudoID in the first line is equal to the the one imported from my main class it will recognise it and not write it. But if this -same- sudoID is in the second row it will not recognise it and will write it again.
For instance, if my CSV looks like this it will work:
"Patient_id Pseudo_ID",
"32415","PAT106663926"
If it looks like this it will re-write the sudoID:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
Thanks!
My Code:
public class CSVConnection {
#SuppressWarnings({ "deprecation", "resource", "rawtypes", "unchecked" })
public String getID(String sID,String pseudoID) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
try {
CsvToBean csv = new CsvToBean();
String csvFilename = "CsvFile.csv";
Writer writer= new FileWriter(csvFilename,true);
CSVReader csvReader = new CSVReader(new FileReader(csvFilename),',','"',1);
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(PatientCSV.class);
String[] columns = new String[] {"patID","pseudoID"};
strategy.setColumnMapping(columns);
//Set column mapping strategy
StatefulBeanToCsv<PatientCSV> bc = new StatefulBeanToCsvBuilder<PatientCSV>(writer).withMappingStrategy(strategy).build();
List patList = csv.parse(strategy, csvReader);
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String [] args) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
CSVConnection obj = new CSVConnection();
String sID="32415";
String pseudoID="PAT101830150";
obj.getID(sID,pseudoID);
}
}
and the Java Bean :
public class PatientCSV {
private String patID;
private String pseudoID;
public String getPatID() {
return patID;
}
public void setPatID(String patID) {
this.patID = patID;
}
public String getPseudoID() {
return pseudoID;
}
public void setPseudoID(String pseudoID) {
this.pseudoID = pseudoID;
}
public PatientCSV(String patID, String pseudoID) {
super();
this.patID = patID;
this.pseudoID = pseudoID;
}
public PatientCSV() {
super();
// TODO Auto-generated constructor stub
}
public String toString()
{
return "Patient [id=" + patID + ", pseudoID=" + pseudoID + "]";
}
}
Lets inspect your for loop
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
So in the case you mention it is not working as expected, meaning that the line that matches your input is the second line:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
So you call: getID("32415", "PAT106663926")
What happens in your loop is:
You take the first element of your csv patients, the one with id: 32416,
check if it matches with the id given as input to your method, 32415.
It does not match so it goes to the else part. There it creates the new patient (with the same patID and pseudoID as the 2nd row of your csv) and stores it in the file.
So by now you should have 2 entries in your csv with the same data "32415","PAT106663926".
I think that this is the error, in your for loop you should check against all entries if there is a match, and then create the patient and store it to the csv.
An example:
PatientCSV foundPatient = null;
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
foundPatient = pat;
}
}
if (foundPatient == null) {
foundPatient = new PatientCSV();
foundPatient.setPatID(sID);
foundPatient.setPseudoID(pseudoID);
patList.add(foundPatient);
/*Find a way to import it to the CSV*/
bc.write(foundPatient);
writer.close();
}
return foundPatient.getPseudoID();
P.S. The above example is written very quickly, just to give you the idea what needs to be done.
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
I am able to load files in Fixed Format but unable to write a fixed format file using FixedFormat4j.
Any idea how to do that?
public class MainFormat {
public static void main(String[] args) {
new MainFormat().start();
}
private FixedFormatManager manager;
public void start(){
System.out.println("here");
manager = new FixedFormatManagerImpl();
try {
BufferedReader br = new BufferedReader(new FileReader("d:/myrecords.txt"));
System.out.println("here1");
String text;
MyRecord mr = null;
while ((text = br.readLine()) != null) {
mr = manager.load(MyRecord.class, text);
System.out.println(""+mr.getAddress() + " - "+mr.getName());
}
mr.setName("Rora");
manager.export(mr);
} catch (IOException | FixedFormatException ex) {
System.out.println(""+ex);
}
}
}
I have seen export method but don't understand how to use it? Nothing happens in above code
The export method returns a string representing the marshalled record.
In your code you would need to write out the result of the export command to a FileWriter. So:
before the while loop:
FileWriter fw = new FileWriter("d:/myrecords_modified.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
after the while loop:
mr.setName("Rora");
String modifiedRecord = manager.export(mr);
bw.write(modifiedRecord);
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.)