java typing into file, file not showing, using bytes - java

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();
}
}

Related

Unable to write to file - why?

I am attempting to save to long term file storage in android as well as create a new file in the process. This code keeps crashing with minimal helpful logcat.
Thanks.
public void save (String text) {
FileOutputStream fos = null;
try {
fos = openFileOutput("logfile.txt", MODE_PRIVATE);
fos.write(text.getBytes());
} catch (FileNotFoundException e)
{} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null)
{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I expect it to create a file called logfile.txt and print text to it but instead it crashes.
Try something alike this, in order to get a FileOutputStream from a File in tmp / private storage:
// File file = File.createTempFile("logfile", ".txt");
File file = new File(getFilesDir(), "logfile.txt");
FileOutputStream fos = new FileOutputStream(file);
The resulting path should be /data/data/tld.domain.package/files/logfile.txt.
file.getAbsolutePath() has the value.
See Save a file on internal storage.

ObjectInputStream gives IOException when readObject() is called

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.

IOUtils.write creates new file but doesn't write data

using IOUtils.write to write a string to a file
try {
IOUtils.write("test", new FileWriter(configFile));
} catch (Exception e) {
e.printStackTrace();
}
where configfile is the location of the configuration file ("./resources/config.json")
This seems to delete the file and replace it with a file that has no contents.
no exceptions are thrown either.
Make sure to close the stream after use, else the data might not be written to the file.
FileWriter fw=null;
try {
fw= new FileWriter(configFile);
IOUtils.write("test",fw);
}catch (Exception e) {
e.printStackTrace();
}finally
{
IOUtils.closeQuietly(fw);
}
You need to close the writer, or use try with resources. Otherwise everything might not be flushed to disk:
try (FileWriter fw = new FileWriter(configFile)) {
IOUtils.write("test", fw);
} catch (IOException e) {
e.printStackTrace();
}
Try this code:
FileWriter fw = null;
try {
fw = new FileWriter(configFile);
IOUtils.write("test", fw);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fw != null)
fw.close();
}

File writer not typing in file (Java)

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();
}
}
}

How to delete only the content of a file in Java?

How can I delete the content of a file in Java?
How about this:
new RandomAccessFile(fileName).setLength(0);
new FileOutputStream(file, false).close();
You could do this by opening the file for writing and then truncating its content, the following example uses NIO:
import static java.nio.file.StandardOpenOption.*;
Path file = ...;
OutputStream out = null;
try {
out = new BufferedOutputStream(file.newOutputStream(TRUNCATE_EXISTING));
} catch (IOException x) {
System.err.println(x);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
Another way: truncate just the last 20 bytes of the file:
import java.io.RandomAccessFile;
RandomAccessFile file = null;
try {
file = new RandomAccessFile ("filename.ext","rw");
// truncate 20 last bytes of filename.ext
file.setLength(file.length()-20);
} catch (IOException x) {
System.err.println(x);
} finally {
if (file != null) file.close();
}
May problem is this leaves only the head I think and not the tail?
public static void truncateLogFile(String logFile) {
FileChannel outChan = null;
try {
outChan = new FileOutputStream(logFile, true).getChannel();
}
catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Warning Logfile Not Found: " + logFile);
}
try {
outChan.truncate(50);
outChan.close();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Warning Logfile IO Exception: " + logFile);
}
}
Open the file for writing, and save it. It delete the content of the file.
try {
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.flush();
writer.close();
}catch (Exception e)
{
}
This code will remove the current contents of 'file' and set the length of file to 0.

Categories

Resources