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.
Related
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();
}
}
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.
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.
I try to get large arrays from java into matlab.
My problem ist, the java program is to large to run java in matlab, so I need to export the data from java and load it into matlab. Do anyone tried this?
This is how far I got:
I've wrote a class containing all values that should be exported
------- Export.java -------
import java.io.Serializable;
public class Export implements Serializable {
private double[][] values;
private String description;
public Export(String description,double[][] values){
this.description=description;
this.values=values;
}
public String getDescription(){return description;}
public double[][] getValues(){return values;}
}
--------------------------
And an main methode
------- StartPoint.java -------
public class StartPoint {
public static void main(String[] args) {
Export serial= new Export("description",new double[][]{{1,2},{3,4}});
OutputStream file;
try {
file = new FileOutputStream( "object.ser" );
OutputStream buffer = new BufferedOutputStream( file );
ObjectOutput output = new ObjectOutputStream( buffer );
output.writeObject(serial);
output.close();
}
catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
System.out.println("done");
}
}
--------------------------
Accroding to http://www.weizmann.ac.il/matlab/techdoc/matlab_external/ch_java9.html the matlab-code should be easy, but I don't get ist. So any help for the matlab code would be great.
Thanks
To facilitate the import in Matlab I suggest that you write the data using the MAT-file format. Then you will be able to load the files into Matlab variables.
I am able to create log files using FileAppender, RollingFileAppender,etc.,
My Problem is that the logs are written as plain text that anyone can read, but I want to register my logs as Binary Files that are not human readable.
Can anyone help me with the suggestion to create a Binary log file for an example code.
Its not such a good Idea to do what you wrote, but if you really need to, write an own appender like this:
package de.steamnet.loggingUtils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
public class BinaryAppender extends AppenderSkeleton {
FileOutputStream fout;
public BinaryAppender() throws FileNotFoundException {
fout = new FileOutputStream("/tmp/somefile.log.bin");
}
#Override
protected void append(LoggingEvent le) {
String origMessage = le.getLoggerName() + " said: " + le.getMessage();
byte[] obscure = origMessage.getBytes();
for(int ii = 0; ii < obscure.length; ii++) {
if(obscure[ii] == Byte.MAX_VALUE) {
obscure[ii] = Byte.MIN_VALUE;
} else {
obscure[ii] = (byte)(obscure[ii] +1); // thats a really bad idea to create 'nonesense stuff' that way!
}
}
try {
fout.write(obscure);
} catch (IOException ex) {
System.out.println("too bad. File writer bombed.");
}
}
#Override
public boolean requiresLayout() {
return false; // we do all layouting in here.
}
#Override
public void close() {
try {
fout.close();
} catch (IOException ex) {
System.out.println("too bad. could not close it.");
}
}
}
Then in your log4j config use this class as appender and you are done with the writing part. for the reading part you again need to read it byte per byte and reduce the byte by one and then load a string from it.
Good luck.
I would use DataOutputStream BufferedOutputStream and FileOutputStream to write binary files. I assume you want the files to be machine readable rather than non-readable. ;)
Log4j is designed for text files, however you can use its logging levels like.
private static final Log LOG =
static DataOutputStream out = ... FileOutputStream ...
if(LOG.isDebugEnabled()) {
// write a debug log to out
}