Java File I/O - Text File - How to check for content? - java

I was wondering, If i had a java class, that wanted to consult a txt file with say a list of names like
tom
steve
jones
how could i open the text file in the java program and basically see if a string contained in the program matches one of these names?
so far i have come up with
try {
BufferedReader inputReader = new BufferedReader(new FileReader("users.txt"));
while (inputReader.readLine() != null){
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException ep) {
// TODO Auto-generated catch block
p.printStackTrace();
}
but do not no where to go from here..

You need to store the result of readLine(), like:
String nextLine;
while ((nextLine = inputReader.readLine()) != null){
if (nextLine.equals(stringToCheck)) {
//do something
}
}
(where stringToCheck is the target string, of course.)

Related

How do I print the next element in a linked list to a CSV file?

I'm making an address book and my program is supposed to save each element in a list to a CSV file. I've gotten everything to work asside from the fact that it will only save 1 line to the file.
public static void save(){
PrintWriter writer = null;
try {
writer = new PrintWriter("C:\\Users\\Remixt\\workspace\\2\\AddressBook.csv", "UTF-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
{
writer.println(AddressBook.get(getListSize()-1)+"\n");
writer.close();//saves file
}
Edit: It will only save the last element to the file. It only shows 1 thing in the file no matter how many times i add something else to the list.
the problem is here
writer.println(AddressBook.get(getListSize()-1)+"\n");
you just write the last element of AddressBook to the csv file, use for loop
the following is a sample
for (int i = 0; i < AddressBook.size(); i++) {
writer.println(AddressBook.get(i)+"\n");
}
at last, you should write file by append mode
filename=new FileWriter("printWriter.txt",true);
writer=new java.io.PrintWriter(filename);

xml format in stanford pos tagger

i have tagged 20 sentences and this is my code:
public class myTag {
public static void main(String[] args) {
Properties props = new Properties();
try {
props.load(new FileReader("D:/tagger/english-bidirectional-distsim.tagger.props"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MaxentTagger tagger = new MaxentTagger("D:/tagger/english-bidirectional-distsim.tagger",props);
//==================================================================================================
try (BufferedReader br = new BufferedReader(new FileReader("C:/Users/chelsea/Desktop/EN/EN.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
String tagged = tagger.tagString(sCurrentLine);
System.out.println(tagged);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is the output:
as you can see in sentence node it has a Id attribute and here it's constantly=0 which it should not be.i expect the value=0,1,2,3,4,...
i don't understand what is wrong with my code.
Stanford POS tagger (strictly speaking, sentence splitter that is applied before POS annotator) generates ids for sentences per input text.
So, you ask tagger to tag sCurrentLine consisting of one sentence, this text is split into sentences - actually, just one, with id = 0; then you ask to tag another text - sCurrentLine from the next iteration - and it again is the only sentence and thereby it is the first sentence with id = 0; and so on.
Thus, if you want correct ids, firstly create the whole text, then pass it to tagger. However, if your input text is already split by sentences, it'll be better to leave things as they are (and generate ids by yourself in the loop, if you need them).

Java: Create a KML File and insert elements in existing file

I`m developing an app that reads the GPS-Exif Information of Photos and writes the Tags (Lat/Lon,...) in an KML or CSV File.
Creating the Files if they dont exist, especially the csv, is not the problem, but in this case i want to add a new KML- placemark to an existing KML-file.
so far i have created a method that checks if the file already exists - if not (if-statement) it creates a new one.
and if the file exists it should add the information (else).
public void createKMLFile(){
String kmlstart = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n";
String kmlelement ="\t<Placemark>\n" +
"\t<name>Simple placemark</name>\n" +
"\t<description>"+name+"</description>\n" +
"\t<Point>\n" +
"\t\t<coordinates>"+latlon[1]+","+latlon[0]+","+z+ "</coordinates>\n" +
"\t</Point>\n" +
"\t</Placemark>\n";
String kmlend = "</kml>";
ArrayList<String> content = new ArrayList<String>();
//content.add(0,kmlstart);
//content.add(1,kmlelement);
//content.add(2,kmlend);
String kmltest;
//Zum Einsetzen eines Substrings (weitere Placemark)
//String test = "</kml>";
//int index = kml.lastIndexOf(test);
File test = new File(datapath+"/"+name+".kml");
Writer fwriter;
if(test.exists() == false){
try {
content.add(0,kmlstart);
content.add(1,kmlelement);
content.add(2,kmlend);
kmltest = content.get(0) + content.get(1) + content.get(2);
fwriter = new FileWriter(datapath+"/"+name+".kml");
fwriter.write(kmltest);
//fwriter.append("HalloHallo", index, kml.length());
fwriter.flush();
fwriter.close();
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else{
kmltest = content.get(0) + content.get(1) + content.get(2);
StringTokenizer tokenize = new StringTokenizer(kmltest, ">");
ArrayList<String> append = new ArrayList<String>();
while(tokenize.hasMoreTokens()){
append.add(tokenize.nextToken());
append.add(1, kmlelement);
String rewrite = append.toString();
try {
fwriter = new FileWriter(datapath+"/"+name+".kml");
fwriter.write(rewrite);
fwriter.flush();
fwriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I dont get any Logs in the LogCat but the App stops working if i try to update the existing file... any suggestions?
thanks in advance
EDIT: Ok i see that content.add(0, kml...) has to be outside the try block... but thats not the main problem it seems
When modifying XML files it is best accomplished using a library of some sort. I maintain the XML-manipulation library called JDOM which is designed to make this sort of manipulation as easy as it can. Other options are using the DOM library (which is already built in to the Java runtime which makes it much easier to integrate in to your program), and SAX (which, in this case, I would not recommend, even though it may be faster). Other external libraries (like JDOM) exist which would also help, like XOM, dom4j, etc. This stackoverflow answer seems relevant: Best XML parser for Java
In JDOM, your code would look something like:
Document doc = null;
Namespace kmlns = new Namespace("http://www.opengis.net/kml/2.2");
Element position = new Element("Position", kmlns);
position.addContent(new Element("name", kmlns).setText(positionName));
position.addContent(new Element("desc", kmlns).setText(description));
position.addContent(..... all the XML content needed for the Position ....);
// create the XML Document in memory if the file does not exist
// otherwise read the file from the disk
if(!test.exists()){
doc = new Document();
Element root = new Element("kml", kmlns);
} else {
SAXBuilder sb = new SAXBuilder();
doc = sb.build(test);
}
Element root = doc.getRootElement();
// modify the XML as you need
// add Position Element
root.addContent(position);
try {
fwriter = new FileWriter(datapath+"/"+name+".kml");
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
xout.output(doc, writer);
fwriter.flush();
fwriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT: you ask what's wrong with your actual code.... There are a few things that are contributing to your problems, but you don't show an actual error, or other indication of how the program 'stops working'.
there are bugs in your code which should throw serious exceptions: kmltest = content.get(0) + content.get(1) + content.get(2); should throw IndexOutOfBoundsException because the content ArrayList is empty (the lines adding values to the ArrayList are commented out....) - but let's assume that they are not....
You never read the file you are changing, so how can you be changing it?
The StringTokenizer delimeter is ">", which is never a good way to parse XML.
You loop through the String tokenizer on evert '>' delimeter, but you never add the token back in to the output (i.e. your output is milling a lot of '>' characters).
You add the kmlelement Position content in the place of every '>' caracter in the document, not just the one that is important.
The FileWriter logic should be ** outside** the loop.... you do not want to modify the file for every token you modify.
It´s working now, thanks for your input rolfl!
In my programm i have implemented the method with the JDOM library which is much more comfortable, anyhow here is the working code of my first try if someone is interested.
The output is not in a pretty format but the kml-file is working..
public void createKMLFile(){
String kmlstart = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n";
String kmlelement ="\t<Placemark>\n" +
"\t<name>Simple placemark</name>\n" +
"\t<description>"+name+"</description>\n" +
"\t<Point>\n" +
"\t\t<coordinates>"+latlon[1]+","+latlon[0]+","+z+ "</coordinates>\n" +
"\t</Point>\n" +
"\t</Placemark>\n";
String kmlend = "</kml>";
ArrayList<String> content = new ArrayList<String>();
content.add(0,kmlstart);
content.add(1,kmlelement);
content.add(2,kmlend);
String kmltest = content.get(0) + content.get(1) + content.get(2);
File testexists = new File(datapath+"/"+name+".kml");
Writer fwriter;
if(!testexists.exists()){
try {
fwriter = new FileWriter(datapath+"/"+name+".kml");
fwriter.write(kmltest);
fwriter.flush();
fwriter.close();
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else{
//schleifenvariable
String filecontent ="";
ArrayList<String> newoutput = new ArrayList<String>();;
try {
BufferedReader in = new BufferedReader(new FileReader(testexists));
while((filecontent = in.readLine()) !=null)
newoutput.add(filecontent);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
newoutput.add(2,kmlelement);
String rewrite ="";
for(String s : newoutput){
rewrite += s;
}
try {
fwriter = new FileWriter(datapath+"/"+name+".kml");
fwriter.write(rewrite);
fwriter.flush();
fwriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

InputStreamReader is not reading č ž š characters

I'm working on a project, but when I am reading from file it can't read some characters (like č , ž , š, etc.) I dont know what am I am doing wrong.
Here is my code:
try {
reader = new InputStreamReader(getAssets().open("koce_podatki.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(reader);
for(int i=-1;i<position;i++){
try {
temp = "" + br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Your problem is one of encoding. Files only store bytes.
There are many ways to map bytes to characters (those ways are called encoding).
When you read from a text file, you must know and specify which encoding to use.
If you don't specify the encoding in Java, the platform default encoding will be used, which may or may not be what you want.
In your case it is not what you want. To fix this, find out the correct encoding and specify it in the InputStreamReader constructor.
A common encoding to try would be UTF-8. If you told us what you see instead of those characters, we could help you guess the correct encoding.
Try this way:
try {
reader = new InputStreamReader(getAssets().open("koce_podatki.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = new BufferedReader(reader);
while( (s = in.readLine()) != null) {
String UTF8Str = new String(s.getBytes(),"UTF-8"));
temp=""+UTF8Str;
}

Reading unicode characters from csv file

I have a csv file which contains words in english followed by their Hindi translation. I am trying to read the csv file and do some further processing with it. The csv file looks like so:
English,,Hindi,,,
,,,,,
Cat,,बिल्ली,,,
Rat,,चूहा,,,
abandon,,छोड़ देना,त्याग देना,लापरवाही की स्वतन्त्रता,जाने देना
I am trying to read the csv file line by line and display what has been written. The code snippet (Java) is as follows:
//Step 2. Read csv file and get the string.
FileInputStream fis = null;
BufferedReader br = null;
try {
fis = new FileInputStream(new File(csvFile));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
boolean startSeen = true;
if(fis != null) {
try {
br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
System.out.print("Unsupported encoding");
}
String line = null;
if(br != null) {
try {
while((line = br.readLine()) != null) {
if(line.contains("English") == true) {
startSeen = true;
}
if((startSeen == true) && (line != null)) {
StringBuffer sbuf = new StringBuffer();
//Step 3. Parse the line.
sbuf.append(line);
System.out.println(sbuf.toString());
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
However, the following output is what I get:
English,,Hindi,,,
,,,,,
Cat,,??????,,,
Rat,,????,,,
abandon,,???? ????,????? ????,???????? ?? ???????????,???? ????
My Java is not that great and though I have gone through a number of posts on SO, I need more help in figuring out the exact cause of this problem.
For reading text file it is better to use character stream e.g by using java.util.Scanner directly instead of FileInputStream. About encoding you have to make sure first that the text file that you want to read is saved as 'UTF-8' and not otherwise. I also notice in my system, I have to save my java source file as 'UTF-8' as well to make it shown hindi char properly.
However I want to suggest simpler way to read csv file as follow:
Scanner scan = new Scanner(new File(csvFile));
while(scan.hasNext()){
System.out.println(scan.nextLine());
}
I think your console cannot show Hindi chars. Try
System.out.println("Cat,,बिल्ली,,,");
to test
So as discussed in above answers; solutions it is TWO steps
1) Save your txt file as UTF-8
2) Change the property of your Java code to use UTF-8
In Eclipse; right click on Java file;
Properties -> Resurces -> Text File Encoding -> Other -> UTF-8
Refer screenshot given on
http://howtodoinjava.com/2012/11/27/how-to-compile-and-run-java-program-written-in-another-language/

Categories