Get data from rdf file [duplicate] - java

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Java - Using Jena APi - Get data from RDF file
I'm using Java and Jena API.
I have the class Person with the datatype properties hasFirstName, hasLastName, hasDateOfBirth, hasGender.
Here is how one person is represented in my RDF file.
<rdf:Description rdf:about="http://www.fam.com/FAM#Bruno04/02/1980 ">
<j.0:FAMhasGender>H</j.0:FAMhasGender>
<j.0:FAMhasDateOfBirth>04/02/1980</j.0:FAMhasDateOfBirth>
<j.0:FAMhasLastName>DS </j.0:FAMhasLastName>
<j.0:FAMhasFirstName> Bruno</j.0:FAMhasFirstName>
</rdf:Description>
I'd like to get for each person the firstname, gender, date of birth and write that information in a text file. The problem I have is that it only writes the first woman/man he finds in the rdf file, but there is more than one woman and man.
Can you please explain me how can I solve this?
Thank you very much.
ExtendedIterator instances = onto.person.listInstances();
Individual instance = null;
Individual firstInstance = null;
while (instances.hasNext()) {
instance = (Individual) instances.next();
gen = instance.getPropertyValue(onto.hasGender).toString();
fname = instance.getPropertyValue(onto.hasFirstName).toString();
dd = instance.getPropertyValue(onto.hasDateOfBirth).toString();
writeFile(fname, dd, genr);}
// Write text file
public void writeFile(String fn, String dbir, String gn) {
String fileout = "D:/file1.txt";
String firstName = fn;
String dateB = dbir;
String gender = gn;
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(fileout, true));
if (gender.equals("F")) {
out.write("[label= \"" + firstName + " \"\n\n\"D.Naiss:" + dnai1 + "\", " + shape + "]");
} else if (gender.equals("M")) {
out.write("[label= \"" + firstName + " \"\n\n\"D.Naiss:" + dnai1 + "\", " + shape2 + "]");
}
out.newLine();
// flushes and closes the stream
out.close();
} catch (IOException e) {
System.out.println("There was a problem:" + e);
}
}

Your problem has nothing to do with Jena or RDF but is rather a logic error in your coding.
You call writeFile() inside your while loop which opens a new file, writes the current entry and closes the file. So you are repeatedly overwriting your file with a single entry at one time so you will only ever end up with a single person in the file.
You need to refactor the code to open the file once before the while loop, have the writeFile() method simply add to that file (and not close it) and then close the file after the while loop.
Also as #Udo Kilmaschewski pointed out in your apparent duplicate the genr variable is not defined in the code you showed so you don't appear to be correctly passing the gender from your while loop to the writeFile() function.

Related

Appending in Serialization

So far I have found that there is a way to do appending in serialization by making a sub-class but that seems like a lengthy way. Is there any better way to do appending in serialization?
I have this vectorlist in a class named Course
private Vector<Student> StudentList = new Vector<>();
I have 2 objects of course.
3 students are enrolled in 1 course and 2 students are enrolled in another. Now I call this method which is doing serialization in the file but when I call it with my 2nd course object, it replaces previous content.
public void Serialization() {
try {
File file = new File("EnrolledStudentsSerial.txt");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fo = new FileOutputStream(file);
ObjectOutputStream output = new ObjectOutputStream(fo);
output.writeObject("Course: " + this.name + "\n\nEnrolled Students: ");
for (int i = 0; i < StudentList.size(); i++) {
Student p_obj = StudentList.elementAt(i);
String content = "\n\tStudent Name: " + p_obj.getName() + "\n\tStudent Department: " + p_obj.getDepartment() + "\n\tStudent Age: " + p_obj.getAge() + "\n";
output.writeObject(content);
}
output.writeObject("\n");
fo.close();
} catch (IOException ioe){
System.out.println("Error: " + ioe.getMessage());
}
}
If you want to append to a file, instead of replacing the content, you need to tell the FileOutputStream that, by adding an extra argument and call FileOutputStream(File file, boolean append). FYI: don't do that with an ObjectOutputStream.
You don't need to call createNewFile(), since FileOutputStream will do that, whether appending or not.
However, you are not actually serializing your objects, since you're serializing strings instead. What you're doing makes no sense. Since you seem to want the result to be a text file (you're writing text, and file is names .txt), you should forget about ObjectOutputStream, and use a FileWriter instead.
Better yet, instead of using the old File I/O API, you should be using the "newer" NIO.2 API that was added in Java 7. You should also be using try-with-resources. Same goes for the ancient Vector class, which was replaced by ArrayList in Java 1.2.
Java naming convention is for field and method names to start with lowercase letter. And since your method is not "serializing" anymore, you should give it a better name.
Applying all that, your code should be:
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
private ArrayList<Student> studentList = new ArrayList<>();
public void writeToFile() {
Path file = Paths.get("EnrolledStudentsSerial.txt");
try (BufferedWriter output = Files.newBufferedWriter(file, CREATE, APPEND, WRITE)) {
output.write("Course: " + this.name + "\n\nEnrolled Students: ");
for (Student student : studentList) {
String content = "\n\tStudent Name: " + student.getName() +
"\n\tStudent Department: " + student.getDepartment() +
"\n\tStudent Age: " + student.getAge() + "\n";
output.write(content);
}
output.write("\n");
} catch (IOException ioe){
System.out.println("Error: " + ioe.getMessage());
}
}

BufferedWriter write string line by line

Hello I am building a program that writes an output to a text file.
In my program my String looks like this:
MyName
Addres
Location
Paycheck
But when I write it to a text file it looks like this:
MyName Addres Location Paycheck
I am writing everything from a single toString method. How can I use bufferedwriter so that it formats the string while writing it?
Here's my code:
if (file != null) {
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter out = new BufferedWriter(fileWriter);
try {
out.write(emp.toString());
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT:
Here is the toString method for the emp class:
#Override
public String toString() {
return "Name: " + name + " \nDOB: " + dob + " \nAddress: " + address + " \n******Paycheck******\nSalary: "
+ myPaycheck.getSalary() + "\nFederal Income: " + myPaycheck.getTaxes() + "\nSocial Security: "+ myPaycheck.getSocialSecurity() + "\nMedicare: " + myPaycheck.getMedicare()
+ "\nNet Salary: " + myPaycheck.getNetPay() + "";
}
bufferedwriter API
You can use "newLine" easily .
bw.newLine();
You either need to use System.lineSeparator() while writing text to file or change your toString() method to add a line separator between each line or object added
Edit
Your code writes your string as separate line only. Try reading the lines from output file and print each line, you will see that the reader treats each detail as separate line. Now if you wish to write it into the file with exact format so that it is shown in next line in file u have to give the inputs separately maybe by adding the objects to an ArrayList and iterating the same.

How do I change the directory a PrintWriter saves to in Java?

My program takes in user input, and puts it into a PrintWriter.
I am unsure of how to change the directory that the PrintWriter saves the text file to. I also need the name of the files to dynamically change based on user input. Here is the code for the PrintWriter:
PrintWriter writer = new PrintWriter(
"ChangeLog" + textField.getText() + textField_1.getText() + textField_9.getText() + ".txt",
"UTF-8");
writer.println("Version Number: " + version);
writer.println("Start Date: " + textField.getText());
writer.println("Start time: " + textField_1.getText());
if (rdbtnYes.isSelected()) {
writer.println("Change was documented in the IT info sheet.");
}
if (rdbtnNo.isSelected()) {
writer.println("Change was NOT documented in the IT info sheet.");
}
writer.println("Budget Implecation(S): " + textField_2.getText());
writer.println("Server/Network Device: " + textField_3.getText());
writer.println("Process Of Changes Made: " + textField_4.getText());
writer.println("Need(s)/Reason(s) for Change: " + textField_5.getText());
writer.println("Issues/Problems: " + textField_6.getText());
writer.println("Outcome/Results: " + textField_7.getText());
writer.println("Notes/Comments/Other Info" + textField_8.getText());
writer.close();
The constructor you are using takes a String argument - denoting a file name.
File names can be just that; or they can include path information. You want a different path - then change the filename to include that path!
See here or this for relative vs. absolute paths.
One way to do this is that you will need to create a FileWriter object and tell it what location will the file sit where you want to write stuff. Then you'll pass your FileWriter object as an argument to the PrintWriter constructor.
See the example below:
FileWriter writer = new FileWriter("d:\\path_to_directory\\report.txt");
PrintWriter printWriter = new PrintWriter (writer);
Hope this helps! :)

JAVA: Searching,Deleting and Formatting in a text file

I am making a Flight reservation system for my course project and I am having problems using StringBuilder which my teacher asked me to use in my code.
I wrote this method to delete a customer's data from a text file which I am using for storing the customer's details and the ticket number I assigned to them now this method takes the ticket number and searches in the text file and delete that entry (line of text file).
The text file is formatted in this way
(name + "\t" + socialNum + "\t" + cellNum + "\t" + tickNum + "\n")
The problem is that when I check the text file manually I see that The file was correctly formatted before but after running this method it is not.( The last escape sequence i.e "\n" is not being printed to the file).
public static void deleteData(String b) throws FileNotFoundException {
Scanner input = new Scanner(Basic.file); // Text file used as Database
while (input.hasNext()) {
String a = input.nextLine();
a = a.trim();
a = a.toUpperCase(Locale.ROOT);
if (a.contains(b)) {
continue;
}
Basic.c.append(a).append("\n"); // c is StringBuilderObj
}
if ((Basic.c.toString()).equals("")) {
System.out.println("Invalid Ticket Number.");
} else {
try (PrintWriter out = new PrintWriter(Basic.file)) {
String result = Basic.c.toString();
out.println(result);
}
}

Java: BufferdWriter prints String into two lines for no reason?

I am currently writing a "text check" program in Java, but somehow I got stuck whilst creating an unique identifier for every file.
Actually I create an new identifier like this:
String identifier = Base64.encode((dateFormat.format(date) + "#" + uuid.toString() + "#" + name+".sc0").getBytes()).replace("=", "");
Also my program creates a new file and opens a BufferedWriter.
Actually when I now try to append (I tried using BufferedWriter#write, too, but it didn't work either.)
If I write this String into the file now, it looks like this:
BlMjAxNi8wMy8zMSAyMDo0MjowOSMzMThhYjRkNS0yNjFhLTQwNjItODkyOS03NzlkZDIyOWY4Nj
dGVzdC5zYzA
but it should be in only one line like this:
BlMjAxNi8wMy8zMSAyMDo0MjowOSMzMThhYjRkNS0yNjFhLTQwNjItODkyOS03NzlkZDIyOWY4NjdGVzdC5zYzA
At first I thought that it would probably have a problem with me creating a new line after using BufferedWriter#write, so I tried flushing my BufferedWriter before creating a new line. It didn't work either...
PS:
The whole neccessary code:
String name = file.getName().substring(0, ind);
File next = new File(folder.getAbsolutePath(), name+".sc0");
String identifier = Base64.encode((dateFormat.format(date) + "#" + uuid.toString() + "#" + name+".sc0").getBytes()).replace("=", "");
try {
next.delete();
next.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(next));
logger.info("Adding compiler identifier to file ...");
writer.write("#Script0:"+identifier);
writer.flush();
writer.newLine();
for(String str : lines) {
writer.newLine();
writer.append(str);
}
writer.flush();
writer.close();
} catch (IOException e) {
logger.error("Strange bug ... Did you delete the file? Please try again!");
return;
}
It's the encoder, not the BufferedWriter. Base-64 encoding uses a line length of (I believe) 72 characters.

Categories