I have this method in spring service layer. But it cannot write to file and there is no exception. What's wrong with my code?
public void addLineToFile(String file, String line) {
try {
ClassPathResource cpr = new ClassPathResource(file);
FileOutputStream outputStream = new FileOutputStream(cpr.getFile());
outputStream.write(line.getBytes());
outputStream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(CustomerToFile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(CustomerToFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
Should call the flush() of FileOutputStream before close of stream.
Related
I'm trying to copy a file with .dat extension from a certain directory decided by the user into the project directory. When I try to read the saved object selected by the user, the program always gives IOException.
File f = new File(chooser.getSelectedFile().getPath());
if(f.exists() && !f.isDirectory()) {
FileInputStream flusso= null;
ObjectInputStream leggiObj=null;
try {
flusso = new FileInputStream(chooser.getSelectedFile().getPath());
System.out.println(chooser.getSelectedFile().getPath());
leggiObj = new ObjectInputStream(flusso);
if (leggiObj.readObject().getClass().equals(DatiProgresso.class)) {
DatiProgresso dp = (DatiProgresso) leggiObj.readObject();//<----THIS LINE GIVES THE EXEPTION
leggiObj.close();
flusso.close();
System.out.println("Ciao");
FileOutputStream fop = new FileOutputStream("salvataggi/" + dp.getNome() + ".dat");
ObjectOutputStream scriviObj = new ObjectOutputStream(fop);
scriviObj.writeObject(dp);
scriviObj.flush();
fop.close();
} else {
JOptionPane.showMessageDialog(this, "Unacceptable file", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (HeadlessException ex) {
System.out.println("HeadlessException");
ex.printStackTrace();
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("IOException");
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException");
ex.printStackTrace();
}
}
}
else
{
JOptionPane.showMessageDialog(this, "Unacceptable file", "Error" ,JOptionPane.ERROR_MESSAGE);
}
DatiProgresso dp = (DatiProgresso) leggiObj.readObject();
This line gives the exception.
leggiObj.readObject().getClass().equals(DatiProgresso.class) - here you read your object from the data stream. On next line you attempt to read 2nd object from the stream. If there is no another object then stream fails.
I have created an array of objects of type Employee and i am putting the objects in a .txt file.
Below is the method that accepts Employee objects a parameter and puts it into the .txt file
public void putDataintoFile(Employee[] obj) {
File file = new File("employeedetails.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
try {
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
fos.close();
}
catch (IOException ex) {
Logger.getLogger(EmployeeService1.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(EmployeeService1.class.getName()).log(Level.SEVERE, null, ex);
}
}
This above method is invoked from a seperate "Execetor class " which then calls my getDataFromFile() method below
public void getDataFromFile() {
System.out.println("Reached HERE");
try {
FileInputStream fin = new FileInputStream("employeedetails.txt");
try {
ObjectInputStream oin= new ObjectInputStream(fin);
try {
Employee e =(Employee)oin.readObject();
System.out.println("Reached HERE");
System.out.println(e.toString());
} catch (ClassNotFoundException ex) {
Logger.getLogger(EmployeeService1.class.getName()).log(Level.SEVERE, null, ex);
}
oin.close();
fin.close();
}
catch (IOException ex) {
Logger.getLogger(EmployeeService1.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(EmployeeService1.class.getName()).log(Level.SEVERE, null, ex);
}
}
On executign I get an error which says.
Exception in thread "main" java.lang.ClassCastException: [LMypackage.Employee; cannot
be cast to Mypackage.Employee
at Mypackage.EmployeeService1.getDataFromFile(EmployeeService1.java:225)
at Mypackage.Executor.main(Executor.java:71)
I have implemented Serializable interface in my Employee Classs
Can anyone help me ?
You're writing an array and trying to read a single object.
This is stated in the exception message, which leads to the read/write code, which is fairly obvious despite all the superfluous vertical whitespace.
Also, in general, don't call not-text files .txt.
i need some help here.
I changed a int to an hex after that changing it to byte and tried writing it into a file.
But the file does not appear in the directory as the jar file i build.
File ModFile =new File(NameText.getText() + ".mod");
FileOutputStream writer = null;
String toProcess = CodesBox.getText();
int i = Integer.parseInt(CodesBox.getText());
byte codes = (byte) i;
try {
writer = new FileOutputStream(ModFile);
writer.write(codes);
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
NameText.getText() is definitely there
and the CodesBox.getText() is also definitely correct.
As you can see this is what i get when i open the generated file in an hex editor.
But i would want this instead.
May i know how to fix this?
I know the output file is "vPTP " with spaces, i need the spaces, thank you
Please use either FileWriter or PrintWriter.
For example:
modFile = new File(NameText.getText() + ".mod");
FileWriter writer = null;
if(!modFile.exists()){
try {
modFile.createNewFile();
writer = new FileWriter(ModFile);
System.out.println("Mod file has been created to the current directory");
writer.write(CodesBox.getText());
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}
}
Try this if you use FileOutputStream as well as to write bytes.
File ModFile =new File(NameText.getText() + ".mod");
FileOutputStream writer = null;
try {
writer = new FileOutputStream(ModFile);
writer.write(CodesBox.getText().getBytes(),0,CodesBox.getText().getBytes().length);
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I made a program to produce a file with numbers in it
But the program is not typing any thing in the file it created!
This is the code:
private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
ModFile=new File(NameText.getText() + ".mod");
FileWriter writer = null;
try {
writer = new FileWriter(ModFile);
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}
if(!ModFile.exists()){
try {
ModFile.createNewFile();
System.out.println("Mod file has been created to the current directory");
writer.write(CodesBox.getText());
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When i create a random file, i don't see any thing when i open it!
Please help
Thanks Amir for helping but i noticed i should use FileOutputStream and DataOutputStream...
So, i need help again cause the same problem appeared :(
File ModFile =new File(NameText.getText() + ".mod");
try {
FileOutputStream fos = new FileOutputStream(ModFile);
DataOutputStream dos = new DataOutputStream(fos);
int i = Integer.parseInt(CodesBox.getText());
dos.writeInt(i);
// and other processing
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try{
dos.close();
} catch(IOException e) {
e.printStackTrace();
}
}
NetBeans said they cannot find the symbol dos at (dos.close();)
Please help me here again
You have to check that file name is present in NameText.getText().
You dont need to create file, if file dont exist FileWriter will create it self.
You should Close file after processing
private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
//check before file name is nt null
File ModFile =new File("somefile" + ".mod");
FileWriter writer = null;
try {
writer = new FileWriter(ModFile);
writer.write("test..................");
// and other processing
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
to use FileOutputStream and write byte array follow the following code
private static void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
//check before file name is nt null
File ModFile =new File("somefile" + ".mod");
FileOutputStream writer = null;
String toProcess = "00D0C0DE00D0C0DE F000000000000000";
try {
writer = new FileOutputStream(ModFile);
writer.write(toProcess.getBytes(),0,toProcess.getBytes().length);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have two methods, one that serialize the Object, and it works ok:
public void record()throws RecordingException
{
ObjectOutputStream outputStream = null;
try
{
outputStream = new ObjectOutputStream(new FileOutputStream("src/data/employee.dat"));
outputStream.writeObject(this);
} catch (FileNotFoundException ex)
{
ex.printStackTrace();
throw new RecordingException(ex);
} catch (IOException ex)
{
ex.printStackTrace();
throw new RecordingException(ex);
}finally
{
try
{
if (outputStream != null) outputStream.close();
} catch (IOException ex){}
}
}
The problem here when deserializing the object, I get EOFException!:
public final User loadObject(UserType usertype) throws InvalidLoadObjectException
{
ObjectInputStream istream = null;
String path = null;
if (usertype == UserType.EMPLOYEE)
{
path = "data/employee.dat";
}else if (usertype == UserType.CUSTOMER)
{
path = "data/customer.dat";
}else
throw new InvalidLoadObjectException("Object is not a sub class of User");
try
{
istream = new ObjectInputStream(ObjectLoader.class.getClassLoader().getResourceAsStream(path));
User u = loadObject(istream);
istream.close();
return u;
}catch (EOFException ex)
{
System.out.println(ex.getMessage());
return null;
}catch(Exception ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
}
}
private User loadObject(ObjectInputStream stream) throws InvalidLoadObjectException
{
try
{
return (User) stream.readObject();
} catch (IOException ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
} catch (ClassNotFoundException ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
}
}
I don't know if this is the cause of your problem, but the code that writes the file has a subtle flaw. In the finally block, you close the stream and ignore any exceptions. If the close() method performs a final flush(), then any exceptions thrown in the flush will go unreported.
Try outputStream.flush() before closing your stream in serialization object.
The file was empty, or didn't contain the full serialization of the object.