Add Fileinput to Treemap - java

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(";");

Related

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());
// }
}

Using java export oracle and obtain the status

I want to use Java export Oracle database, and obtain the export status(indicates success or failure), if the operation failed, should return the reason why failed.
But I have trouble in this problem, the export is success,but the label I defined is always false and return [].
What should I do to get the true status or obtain the failure details.
public class DumpFile {
/**
* Default constructor
*/
public DumpFile() {
}
/**
* #return
* #throws InterruptedException
*/
public static boolean LoadToOracle(String Path) throws InterruptedException {
String importStr = "imp scott/tiger#orcl file="+Path+" full=y ignore=y";
Process process_oracle = null;
boolean flag = false;
List<String[]> processListOracle = new ArrayList<String[]>();
try {
process_oracle = Runtime.getRuntime().exec(importStr);
process_oracle.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(
process_oracle.getInputStream(), "utf8"));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println(line);
String[] content = line.split("\n");
processListOracle.add(content);
}
int exevalue = process_oracle.waitFor();
System.out.println("exevalue:"+exevalue);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
for (String[] line : processListOracle)
for (String temp : line) {
if (temp.trim().equals("successfully"))
flag = true;
}
return flag;
}
public static String exportFromOracle(String FileName) throws InterruptedException {
String Path="/home/oracle/output/";
String exportStr = "exp scott/tiger#orcl file="+Path+FileName;
Process process_oracle = null;
boolean flag = false;
List<String[]> processListOracle = new ArrayList<String[]>();
try {
process_oracle = Runtime.getRuntime().exec(exportStr);
BufferedReader input = new BufferedReader(new InputStreamReader(
process_oracle.getInputStream(), "utf8"));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println("line:"+line);
String[] content = line.split("\n");
processListOracle.add(content);
}
int exevalue = process_oracle.waitFor();
System.out.println("exevalue:"+exevalue);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
for (String[] line : processListOracle)
for (String temp : line) {
if (temp.trim().equals("successfully"))
flag = true;
}
System.out.println("flag:"+flag);
if (flag==true)
return flag+"test"+Path;
else{
for (String[] line : processListOracle)
System.out.println(line);
}
return processListOracle.toString();
}
public static void main(String[] args) throws Exception {
String a=exportFromOracle("test.dmp");
System.out.println("a.isEmpty:"+a.isEmpty());
System.out.println(a);
}
}
OUTPUT:
exevalue:0
a.isEmpty:false
[]
I have solved this problem by "log file", I use imp export the database and output the log file, then I use Java to read the log file, to obtain the status.

Output issues: Passing from BufferedReader to array method

I've compiled and debugged my program, but there is no output. I suspect an issue passing from BufferedReader to the array method, but I'm not good enough with java to know what it is or how to fix it... Please help! :)
public class Viennaproj {
private String[] names;
private int longth;
//private String [] output;
public Viennaproj(int length, String line) throws IOException
{
this.longth = length;
this.names = new String[length];
String file = "names.txt";
processFile("names.txt",5);
sortNames();
}
public void processFile (String file, int x) throws IOException, FileNotFoundException{
BufferedReader reader = null;
try {
//File file = new File("names.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sortNames()
{
int counter = 0;
int[] lengths = new int[longth];
for( String name : names)
{
lengths[counter] = name.length();
counter++;
}
for (int k = 0; k<longth; k++)
{
int counter2 = k+1;
while (lengths[counter2]<lengths[k]){
String temp2;
int temp;
temp = lengths[counter2];
temp2 = names[counter2];
lengths[counter2] = lengths[k];
names[counter2] = names[k];
lengths[k] = temp;
names[k] = temp2;
counter2++;
}
}
}
public String toString()
{
String output = new String();
for(String name: names)
{
output = name + "/n" + output;
}
return output;
}
public static void main(String[] args)
{
String output = new String ();
output= output.toString();
System.out.println(output+"");
}
}
In Java, the public static void main(String[] args) method is the starting point of the application.
You should create an object of Viennaproj in your main method. Looking at your implementation, just creating an object of Viennaproj will fix your code.
Your main method should look like below
public static void main(String[] args) throws IOException
{
Viennaproj viennaproj = new Viennaproj(5, "Sample Line");
String output= viennaproj.toString();
System.out.println(output);
}
And, if you are getting a FileNotFound exception when you execute this, it means that java is not able to find the file.
You must provide complete file path of your file to avoid that issue. (eg: "C:/test/input.txt")

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

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.)

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