I have a predefined list of phone numbers to block in my application, the list is being created based on a file input in PhoneListFilter constructor.
I need to be able to add and remove items from this list without restarting the application. I was thinking about implementing FileWatcher which could start a thread and check the file for any changes every 5 minutes or so and update the list. Is it a good approach or should I do it differently?
PhoneListFilter.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PhoneListFilter {
private List<String> phoneList;
public PhoneListFilter() {
phoneList = new ArrayList<>();
try {
Scanner s = new Scanner(new File("PhonesToBlockList"));
while (s.hasNext()) {
phoneList.add(s.next());
}
s.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
public boolean shouldBlock(PhoneRequest phoneRequest) {
if (phoneList.contains(phoneRequest.getPhoneNumber())) {
return true;
}
return false;
}
}
Related
Let's say I have theese words in a text file
Dictionary.txt
artificial
intelligence
abbreviation
hybrid
hysteresis
illuminance
identity
inaccuracy
impedance
impenetrable
imperfection
impossible
independent
How can I make each word a different object and print them on the console?
You can simple use Scanner.nextLine(); function.
Here is the following code which can help
also import the libraries
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
Use following code:-
String []words = new String[1];
try{
File file = new File("/path/to/Dictionary.txt");
Scanner scan = new Scanner(file);
int i=0;
while(scan.hasNextLine()){
words[i]=scan.nextLine();
i++;
words = Arrays.copyOf(words,words.legnth+1); // Increasing legnth of array with 1
}
}
catch(Exception e){
System.out.println(e);
}
You must go and research on Scanner class
This is a very simple solution using Files:
package org.kodejava.io;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
public class ReadFileAsListDemo {
public static void main(String[] args) {
ReadFileAsListDemo demo = new ReadFileAsListDemo();
demo.readFileAsList();
}
private void readFileAsList() {
String fileName = "Dictionary.txt";
try {
URI uri = Objects.requireNonNull(this.getClass().getResource(fileName)).toURI();
List<String> lines = Files.readAllLines(Paths.get(uri),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Source: https://kodejava.org/how-do-i-read-all-lines-from-a-file/
This is another neat solution using buffered reader:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* BufferedReader and Scanner can be used to read
line by line from any File or
* console in Java.
* This Java program
demonstrate line by line reading using BufferedReader in Java
*
* #author Javin Paul
*/
public class BufferedReaderExample {
public static void main(String args[]) {
//reading file line by line in Java using BufferedReader
FileInputStream fis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream("C:/sample.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading
File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
System.out.println(line);
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
fis.close();
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Source: https://javarevisited.blogspot.com/2012/07/read-file-line-by-line-java-example-scanner.html#axzz7lrQcYlyy
These are all good answers. The OP didn't state what release of Java they require, but in modern Java I'd just use:
import java.nio.file.*;
public class x {
public static void main(String[] args) throws java.io.IOException {
Files.lines(Path.of("/path/to/Dictionary.txt")).forEach(System.out::println);
}
}
If I got a .txt file named words.txt and I want to catch the words to input them into an arraylist how do I do that. I know buffered reader exists but I dont quite get how to use it. All words are seperated by a space or an enter key. It has to then for example filter out words that are not 4 characters long and place the 4 long words in an arraylist to use later.
For example I got this txt file :
one > gets ignored
two > gets ignored
three > gets ignored
four > caught and put into for example arraylist
five > 4 long so gets caught and put into arraylist
six > ignored
seven > ignored
eight > ignored
nine > caught because its 4 char long
ten > ignored
You can do it using streams and NIO.2
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Path path = Paths.get("words.txt");
try (Stream<String> lines = Files.lines(path)) {
List<String> list = lines.filter(word -> word.length() == 4)
.collect(Collectors.toList());
System.out.println(list);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Here is my words.txt file:
one
two
three
four
five
six
seven
eight
nine
ten
And running the above code, using the above file, prints the following:
[four, five, nine]
Alternatively, you can use a Scanner
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Path source = Paths.get("words.txt");
try (Scanner scanner = new Scanner(source)) {
List<String> list = new ArrayList<>();
while (scanner.hasNextLine()) {
String word = scanner.nextLine();
if (word.length() == 4) {
list.add(word);
}
}
System.out.println(list);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Note that both the above versions of class Main use try-with-resources.
Yet another way is to use class java.io.BufferedReader (since you mentioned it in your question).
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
File f = new File("words.txt");
try (FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr)) {
List<String> list = new ArrayList<>();
String line = br.readLine();
while (line != null) {
if (line.length() == 4) {
list.add(line);
}
line = br.readLine();
}
System.out.println(list);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
I am having some trouble to find out whats wrong with my code. I've been busy reading other topics with NullPointerExceptions and tried to find it out by using the debugger, I couldn't find a good video to show me how to work with a debugger so I kinda failed to figure it out.
I am using Netbeans and this is a take out from the error output:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at tibianic.spy.system.FileHandler.addVipToList(FileHandler.java:81)
at tibianic.spy.system.FileHandler.loadVipList(FileHandler.java:65)
at tibianic.spy.system.FileHandler.<init>(FileHandler.java:27)
Im assuming the problem is located within the FileHandler Class - loadVipList/addVipToList methods.
The class:
package spy.system;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author unknown
*/
public class FileHandler {
ArrayList<Vip> vip;
public FileHandler() {
this.loadVipList();
}
public void setVipList(ArrayList<Vip> newList) {
this.vip = newList;
}
public ArrayList<Vip> getVipList() {
return this.vip;
}
public void saveVipList() {
String line;
try {
FileWriter fWriter = new FileWriter("vip.txt");
BufferedWriter bWriter = new BufferedWriter(fWriter);
for (Vip v : vip) {
line = v.getName() + ":" + v.getNote();
bWriter.write(line);
}
bWriter.close();
fWriter.close();
} catch (IOException ex) {
Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void loadVipList() {
String line;
String[] person;
try {
FileReader fReader = new FileReader("vip.txt");
BufferedReader bReader = new BufferedReader(fReader);
while ((line = bReader.readLine()) != null) {
person = line.split(":");
addVipToList(person[0],person[1]);
}
bReader.close();
fReader.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void addVipToList(String name, String note) {
Vip guy = new Vip(name,note);
vip.add(guy);
}
}
To my understanding the NullPointerException comes when im giving a object with value null to a method, is that right? I think there is a very small misstake I just cant find because I dont really know what the error message is trying to tell me -
I did cut out a header comment so the lines might not be accurate.
Thanks in advance
Your exception says that your error is located at tibianic.spy.system.FileHandler.addVipToList(FileHandler.java:81)
and based on your code it is thrown in the following method.
private void addVipToList(String name, String note) {
Vip guy = new Vip(name,note);
vip.add(guy);
}
Note that you have
public void setVipList(ArrayList<Vip> newList) {
this.vip = newList;
}
you need to call setVipList() first before you call addVipToList(), since without that the list vip is still null.
I think the problem is because you never initialized the arraylist.
ArrayList<Vip> vip = new ArrayList<Vip>
I didn't call setVipList() and I didn't want to call it - yet changing
public class FileHandler {
ArrayList<Vip> vip;
to
public class FileHandler {
ArrayList<Vip> vip = new ArrayList<>();
solved this, I knew this was easy - so embarrassing.
Well, thanks everyone for your fast responses.
the class seems have problem:
when you new a instance ,it will be invoke method this.loadVipList();
public FileHandler() {
this.loadVipList();
}
but vip is null;
ArrayList<Vip> vip;
so you are better write like this:
ArrayList<Vip> vip = new ArrayList<Vip>();
or
List<Vip> vip = new ArrayList<Vip>();
it will be ok!
I'm trying to fill my HashMap with Strings from the text file (zadania.txt) . It's a simple text file in format like :
Q: question 1
A: answer for question 1
Q: question 2
A: answer for question 2 etc ...
Then I want to write it out on console and here the problem is . It runs , but doesn't write out anything. When I change the source file it works but I'm wondering why it doesn't work with that file ( file is ok, not broken , written in Pages and saved as a text file). Anyone can help ? Here's my code :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
public class testClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("zadania.txt");
try {
Scanner skaner = new Scanner(file);
HashMap<String,String> questions = new HashMap<String,String>();
while(skaner.hasNext()){
String question = skaner.nextLine();
String answer = skaner.nextLine();
questions.put(question, answer);
}
Iterator<String> keySetIterator = questions.keySet().iterator();
while(keySetIterator.hasNext()){
String key = keySetIterator.next();
System.out.println(key + "//** " +questions.get(key));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If you use that path to your file File file = new File("zadania.txt");, you need to put your file zadania.txt in the root folder of project.
Or you can create folder resources put your file there and edit path to File file = new File("resources/zadania.txt");
Your code works for me. So, as Oli Charlesworth already mentioned, you should add some output in the first loop, to check that something gets inserted. If not you seem to have an empty file named zadania.txt.
Some other hints for further java programms:
Close your skaner! If you are using Java 7 you can use the try-with-resources:
try (Scanner skaner = new Scanner(file)){
//...
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Otherwise use the finally construct:
Scanner skaner = null;
try {
skaner = new Scanner(file)
//...
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(skaner != null) {
skaner.close();
}
}
Otherwise you may risk (in larger programms) to run out of file handles. It's best practice to close any resource you open.
Class names should be written (by convention) with a leading capital letter, so in your case it would be TestClass.
If you iterate over both, the key and the value of a Map use the Map.entrySet() method to get both. With large maps this is faster than iterating over the key and the call Map.get() to get the Value.
Here is another option to read your *.txt File and put it into a HashMap
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class App {
public static void main(String[] args) {
Map<String, String> questions = new HashMap<>();
Scanner scanner = null;
try {
scanner = new Scanner(new FileInputStream(new File("zanader.txt")));
while (scanner.hasNext()) {
String question = scanner.nextLine();
String answer = scanner.nextLine();
questions.put(question, answer);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (scanner != null) {
scanner.close();
}
}
// get an iterator
Iterator<Map.Entry<String, String>> itr = questions.entrySet().iterator();
// and go through it
while (itr.hasNext()) {
// get the entryset from your map
Map.Entry<String, String> value = itr.next();
// return only the key
String question = value.getKey();
System.out.println("Get answer by key: " + questions.get(question));
System.out.println("Question: " + value.getKey() + " - Answer: " + value.getValue());
}
}
}
I commented the interesting parts.
Patrick
I am trying to take the contents of an ArrayList and put them into an XML file. Does anyone have a quick,clean and easy solution to this rather that having to use streams and handle exceptions?
For more information, Here is the code I have currently I am getting problem with it, one of which its not creating the file.
package ie.wit.io;
import ie.wit.abs.Device;
import ie.wit.abs.Device;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class FileHandler
{
private FileOutputStream outByteStream;
private ObjectOutputStream OOStream;
private FileInputStream inByteStream;
private ObjectInputStream OIStream;
private File aFile;
public void setUpFile()
{
aFile = new File("data.xml");
}
public boolean isFileEmpty()
{
return (aFile.length() <= 0);
}
public void writeToFile(ArrayList<Device> team)
{
try
{
outByteStream = new FileOutputStream(aFile);
OOStream = new ObjectOutputStream(outByteStream);
OOStream.writeObject(team);
outByteStream.close();
OOStream.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null,"I/O Error" + e + "\nPlease Contact your Administrator :-)");
}
}
currentClass)
public ArrayList<Device> readFromFile()
{
ArrayList<Device> temp = null;
try
{
inByteStream = new FileInputStream(aFile);
OIStream = new ObjectInputStream(inByteStream);
if(!this.isFileEmpty())
temp = (ArrayList<Device>)OIStream.readObject();
inByteStream.close();
OIStream.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null,"I/O Error" + e + "\nPlease Contact your Administrator :-)");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"General Error" + e + "\nPlease Contact your Administrator :-)");
}
return temp;
}
}
There are many libraries to do that task.
Here is what I'm doing so far. Edit as per your requirement.
protected String getDocmentsAsString(List<News> documentsListByIndex) {
if(documentsListByIndex.size()>0){
try {
XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("news", News.class);
return xstream.toXML(documentsListByIndex);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
Im using http://x-stream.github.io/json-tutorial.html
You can use a StringBuilder and generate the XML yourself.. It depends on how many items you want to convert. The fastest way is just pushing out the XML data using a StringBuilder.
I recommend to:
create a XSD
generate JAXB Java classes (e.g. using a Maven Plugin)
create instances of the JAXB Java classes and fill up the data
marshal the JAXB Java classes to XML