package healthbuddy;
/**
*
* #author tpzap_000
*/
import java.io.*;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
import com.thoughtworks.xstream.persistence.PersistenceStrategy;
import com.thoughtworks.xstream.persistence.XmlArrayList;
import java.util.List;
import java.util.Scanner;
public class PersistentDataModelCntl implements Serializable{
private File theFile = new File("PDM.txt");
private XStream xstream = new XStream(new StaxDriver());
public static PersistentDataModelCntl thePDMCntl;
private PersistentDataModel thePDM;
public PersistentDataModelCntl(){
this.readPDMFile();
}
public static PersistentDataModelCntl getPDMCntl(){
if(thePDMCntl == null){
thePDMCntl = new PersistentDataModelCntl();
}
return thePDMCntl;
}
public void readPDMFile(){
try
{
System.out.println("in read file");
StringBuilder fileContents = new StringBuilder();
Scanner in = new Scanner(theFile);
String tempXML;
boolean test = in.hasNextLine();
System.out.println(test);
while(in.hasNextLine()){
fileContents.append(in.nextLine());
System.out.println("reading file contents");
}
tempXML = fileContents.toString();
thePDM = (PersistentDataModel)xstream.fromXML(tempXML);
}
//If the file does not exist, thePDM is instantiated to be a new, empty, PDM file. The file is then written to disk, and then read from disk
// using some recursive stuff. Also creates a test UserList so that I don't get a NullPointerException in the LoginCntl.
catch(FileNotFoundException ex){
System.out.println("FileNotFound");
thePDM = new PersistentDataModel();
thePDM.thePDMFoodList = new FoodList();
thePDM.thePDMMealList = new MealList();
thePDM.thePDMDietList = new DietList();
thePDM.thePDMDiet = new Diet();
//Creates new attributes if things are null.
this.writePDMFile();
this.readPDMFile();
System.out.println("FileNotFound Exception");
}
catch(IOException ex){
System.out.println("IO Exception");
ex.printStackTrace();
}
}
//Problem Code is here:
public void writePDMFile(){
try{
String xml = xstream.toXML(thePDM);
PrintWriter writer = new PrintWriter(theFile);
System.out.println(xml);
writer.println(xml);
}
catch(Exception ex){
System.out.println("There was a problem writing the file.");
}
}
public PersistentDataModel getPDM(){
return thePDM;
}
}
Above is my code. I currently have an app that uses object serialization for it's data persistence, but I'm in the process of converting it to XML. I'm using the Xstream library to create the XML, but I'm having some trouble writing it to disc. Xstream gives me the XML as a String, which I then attempt to write to a text file using PrintWriter. However the text file is empty, but the String I'm attempting to write to it is not. My understanding of PrintWriter is such that you supply it the file name it should be writing to, it attempts to write to that file(creates it if it does not exist), and then it should write the contents of the String to the file.
Any assistance would be greatly appreciated. Not sure where I'm going wrong.
You need to add
writer.close()
to the end of your code. The writer only writes to file when it is closed.
You need to call PrintWriter::flush() or PrintWriter::close().
Try to close PrintWriter after you wrote xml to file
I'm an idiot. I didn't call close on my PrintWriter.
Related
I am trying to work with file stream and i have a problem.
This is my code :
import java.io.*;
import java.util.*;
public class FileIO {
public static void main(String[] args) {
FileOperations myFile = new FileOperations("C:\\My_Programs\\eclipse\\MyJavaFiles\\myFile.txt");
}
private static class FileOperations {
String fileName;
// constructor without argument
FileOperations() {
fileName = "default";
}
/*
* constructor with argument
* argument is assinged into fileName
* fileName is used to open stream for input and output
*/
FileOperations(String argfileName) {
fileName = argfileName;
try {
// open ouput stream
PrintWriter fileOutput = new PrintWriter(new FileOutputStream(fileName));
// open input stream
BufferedReader fileInput = new BufferedReader(new FileReader(fileName));
} catch (IOException v) {
System.out.println(v);
}
}
}
}
My problem is, that if i implement whole FileOperations class in main method, it works fine and i can use fileOutput and fileInput without any problem.
But i wanted to implement those streams in other method and this is where i got stucked.
Why can't i use something like String fileLine = myFile.fileInput.readLine(); in main method? For me, it looks like those streams are not even opened despite they should be.
I am aware that i didn't close fileInput nor fileOuptu, i would close it after working with file.
Thank you for all advices and explanations!
so here's the problem,
i stack on how to create, open, write, and read file, with this code
import java.util.*;
import java.io.*;
class class_Name{
Formatter x; // Variable: creating new file
File file = new File("file.txt"); // Variable: check file existence
//creating txt file
public void creating_file(){
try{
x = new Formatter("file.txt");
}catch(Exception e){
System.out.println("you got an error");
}
}
public int check_file(){
if(file.exists()){
return 1; // in main method, check if file already exists just pass from creating file
}else{
return 0; // in main method if return value 0, then it create new file with "public void creating_file()" method
}
}
so the problem is when i tried to write something in the file, i using class Formatter and it always format all the text data that in it before and class Formatter won't work if public int check_file() is equals to 1 because it skip from creating file using Formatter class and can't just write in the file because variable x undefined
this is the code how i write text in a file
public void recording_to_file(){
x.format(format, args);
}
and to closing file i need to handle error like this
public void close_file(){
try{
x.close();
}catch(Exception e){
file.close();
}
}
}
there was just ton of class that i need to do something with just one file, or maybe there was one simple class that can do all in one like(write, open, read, close), i am new in java, i think maybe in here i can get help, thank you
Take a look at this.
The second argument to the FileWriter costructor (true) tells it to only append data, instead of overwriting any.
import java.util.*;
import java.io.*;
class SomeClass{
Formatter x;
File file = new File("file.txt");
public void creating_file(){
try{
x = new Formatter(new FileWriter(file, true));
}catch(Exception e){
System.out.println("you got an error");
}
}
public boolean check_file(){
return file.exists();
}
}
I was wondering if it was possible to get an object from a FileInputStream without using ObjectInputStream.
Why am I doing this? I've been working on a project recently, it reads .DAT files from a game and converts them to .OBJ - There is a catch to these .DAT files however: Their stream header is ALWAYS 0xFACEAF0E. Is there a way I can get around the restriction ObjectInputStream has on stream headers and get an Object from one of these files?
Here is the code I need help with.
package xan_code;
/*
* Purpose: Determine file extension and run it through the code to move it to an OBJ.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import main.BeginConversion; //Import the conversion code. Returns a string based on the file
import xan_code.dathandler.ReadBinary; //Get the .DAT reading functions
#SuppressWarnings("serial")
public class HandleFiles extends Main { //Extend main to get the log from the opener UI.
static BeginConversion converter = new BeginConversion(); //Get the converter for XML files since this will also read XMLs derived from the .DAT
static String DatText = ""; //The "text" to return for the .DAT (To pack into the decoded file)
static Object _object; //THIS IS THE VARIABLE OF THE OBJECT I NEED IN ORDER TO CONVERT THE .DAT TO A MODEL
#SuppressWarnings("static-access")
public static String convert(File file, boolean isXML, FileInputStream FIS) { //Convert. Passes in the .DAT or .XML file, a boolean to whether or not its extension is .XML, and the FileInputStream from file
if (isXML) { //If it's an XML
String xml = ""; //This is the text to store the XML as a string
String obj = ""; //This is the text to store the WaveFront OBJ (Model format) as a string
try {
xml = new Scanner(file).useDelimiter("\\Z").next(); //use the scanner to get the string of the XML
obj = converter.BeginConvert(xml); //Pass the XML into the java files required to read from the XML and convert it to an OBJ. They return the text from an OBJ file.
} catch (Exception e) {
//Exceptions are handled before, though to be safe...
e.printStackTrace();
}
return obj; //Return that text to Main so I can create the file.
} else { //We have a .DAT
try {
//HELP REQUIRED HERE. NEED TO GET _object FROM THE FILE WITHOUT USING ObjectInputStream
DatText = ReadBinary.Read(file, _object); //Right now this actually returns the text of an XML, but that doesn't matter much at the moment.
} catch (IOException e) {
DatText = "Unexpected error while reading .DAT file!";
e.printStackTrace();
}
return DatText;
}
}
}
You can just strip off the extra bytes that ObjectInputStream should not see first with a FileInputStream.
static class MyObject implements Serializable{
int i;
}
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
MyObject obj = new MyObject();
obj.i = 77;
File testFile = new File("test.dat");
try (FileOutputStream fos = new FileOutputStream(testFile)) {
fos.write(new byte[]{(byte) 0xFA, (byte) 0xCE, (byte) 0xAF, (byte) 0x0E});
try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(obj);
}
}
try (FileInputStream fis = new FileInputStream(testFile)) {
byte b4[] = new byte[4];
fis.read(b4);
try (ObjectInputStream ois = new ObjectInputStream(fis)) {
MyObject newObj = (MyObject) ois.readObject();
System.out.println("newObj.i = " + newObj.i);
}
}
}
I am trying to write a hashset to a text file. Normally, I have no issues with writing to txt as it is simple for me. However, in this case I am absolutely clueless.
A bit of background about the class: it is a hashset of ComputerScientist objects with 2 fields; name, and field of research (and yes, I know what I put to fill up the hashset does not count, I was only trying to test to see if I could get this to work).
I know the basic setup to use filewriter to save strings to hashset which is what a lot of the similar questions which I found on SO dealt with, so those did not really help me.
I am eager to learn, and would appreciate it if snide or insulting comments were left out. And if there is already a similar question which deals with writing hashsets of objects to txt file, I apologize for not seeing it.
import java.util.HashSet;
import java.io.FileWriter;
import java.io.IOException;
/**
* Write a description of class ComputerScientistSet here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class ComputerScientistSet
{
private HashSet<ComputerScientist> computerScientistSet;
private FileWriter computerScientistWriter;
private String fileName;
/**
* Constructor for objects of class ComputerScientistSet
*/
public ComputerScientistSet(){
computerScientistSet = new HashSet<ComputerScientist>();
fileName = "scientist-names.txt";
setComputerScientistSet();
}
private void setComputerScientistSet(){
computerScientistSet.add (new ComputerScientist("Bob", "Robotics"));
computerScientistSet.add (new ComputerScientist("Tim", "VR"));
computerScientistSet.add (new ComputerScientist("Jake", "Nuclear Fision"));
computerScientistSet.add (new ComputerScientist("Joe", "Snapple"));
computerScientistSet.add (new ComputerScientist("Jane", "Magnets"));
computerScientistSet.add (new ComputerScientist("Mary", "PC"));
}
public void writeNames(){
try{
computerScientistWriter = new FileWriter(fileName, true);
computerScientistWriter.write(computerScientistSet);
computerScientistWriter.close();
}
catch(IOException ioException){
System.out.println("Error.");
}
}
}
Update:
Would it help if I include the following code? I am still working out what would go in the parentheses by the .write() line. My brain is fried :/
for (int i = 0; i < computerScientistSet.size(); i++) {
computerScientistWriter.write();
}
Since I assume you want to write the set to a file to read it in later, the best way would be not to reinvent the wheel and to use serialization instead.
public class Person implements java.io.Serializable {
private String name;
// constructor, setter, getter, etc
}
public static void main(String[] args) {
Set<Person> persons = new HashSet<Person>();
persons.add(new Person("foo");
try {
FileOutputStream fileOut = new FileOutputStream("/tmp/persons.data");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
} catch(IOException e) {
e.printStackTrace();
}
try {
FileInputStream fileIn = new FileInputStream("/tmp/persons.data");
ObjectInputStream in = new ObjectInputStream(fileIn);
Set<Person> persons = (Set<Person>) in.readObject();
in.close();
fileIn.close();
} catch(Exception e) {
e.printStackTrace();
}
}
Ended up using this coding:
public void writeNames(){
try{
computerScientistWriter = new FileWriter(fileName, true);
for(ComputerScientist list: computerScientistSet){
computerScientistWriter.write(list.getName() + " , " + "\n" + list.getField() + System.lineSeparator() );
}
computerScientistWriter.close();
}
catch(IOException ioException){
System.out.println("Error.");
}
}
Based on your comments here your output currently shows many entries as: ComputerScientist#7e384e79
Rather than rely on that link, I strongly encourage you to update this question with an example of what your code here would currently output.
When you see output like ComputerScientist#7e384e79 it means the ComputerScientist class isn't overriding the toString() method to show it's state. You can do that to make your technique work. You can do it by hand or use a IDE that offers a refactoring to make it less tedious but you don't get it for free. You'll need it implemented for every class you wish to output this way.
So lets say I have a txt file that I want to write to with a PrintWriter. How come the following code deletes the old contents of the file everytime its called?
Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Test {
public static void main(String[] args) {
writeToFile("foo");
writeToFile("bar");
}
public static void writeToFile(String text) {
try {
PrintWriter printer = new PrintWriter(new File("myTextFile.txt"));
printer.println("Your text is:" + text);
printer.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
}
Output:
Your text is:bar
I'm guessing its something to do with the fact that I'm creating a new PrintWriter or a new File every time the method is being called, but having only one instance being created in the main method failed to work as well.
If you want to add to a file's contents, you need to explicitly open the file for append; the default in most languages is overwrite.
To do so in Java, use new FileWriter("myfile.txt", true). You can then wrap a PrintWriter around that if desired.