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();
}
Related
Below code snippet throws error
1. When input file path is invalid - FILENOTFOUNDEXCEPTION
2. When output file is open in excel - FILENOTFOUNDEXCEPTION saying said file is open in another process
I want to suggest user to either check input file path or close open excel(or open in notepad instead). How do I catch these separately?
try(FileReader fr = new FileReader("D:/Test.log");
BufferedReader br = new BufferedReader(fr);) {
doSomething(br);
//writing to CSV
String[] arr = {"aaa","bbb"};
FileWriter outputfile= new
FileWriter("D:/output.csv",false);
CSVWriter writer = new CSVWriter(outputfile);
writer.writeNext(arr);
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You should separate code to two try/cath statments
BufferedReader br;
try {
FileReader fr = new FileReader("D:/Test.log");
br = new BufferedReader(fr);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error("Input file not found");
} catch (IOException e) {
e.printStackTrace();
}
doSomething(br);
//writing to CSV
String[] arr = {"aaa","bbb"};
try {
FileWriteroutputfile = new FileWriter("D:/output.csv",false);
CSVWriter writer = new CSVWriter(outputfile);
writer.writeNext(arr);
writer.close();
} catch (IOException e) {
e.printStackTrace();
log.error("Output file already in use");
}
I have the following code to write in three files. I have printed the Strings before writing to ensure they have some data in them, the printed Strings show the data given to them by calling this function but on creation of file the files are empty.
Please suggest something.
public static void save(String editedFileText,String srcFileText,String translFileText)throws IOException {
JFileChooser chooser = new JFileChooser();
System.out.println(editedFileText);
System.out.println(srcFileText);
System.out.println(translFileText);
int retrival = chooser.showSaveDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try {
FileWriter edit = new FileWriter(chooser.getSelectedFile()+".txt");
edit.write(editedFileText.toString());
FileWriter srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt");
srcFile.write(srcFileText.toString());
FileWriter trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt");
trans.write(translFileText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Get in the habit of creating all Writers, Readers, InputStreams and OutputStreams in try-with-resources statements. It ensures they will be properly closed:
try (FileWriter edit = new FileWriter(chooser.getSelectedFile()+".txt")) {
edit.write(editedFileText);
}
try (FileWriter srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt")) {
srcFile.write(srcFileText);
}
try (FileWriter trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt")) {
trans.write(translFileText);
}
If you're just writing a single String, you have the option of using Files.write, which allows you to forego the use of a Writer altogether:
Files.write(Paths.get(chooser.getSelectedFile()+".txt"),
editedFileText.getBytes());
Files.write(Paths.get(chooser.getSelectedFile()+"_srcText"+".txt"),
srcFileText.getBytes());
Files.write(Paths.get(chooser.getSelectedFile()+"_translFile"+".txt"),
translFileText.getBytes());
Add a finally to close the opened files, but first you need to declare them outside the try catch finally:
FileWriter edit,srcFile, trans;
edit = srcFile = trans = null;
try {
edit = new FileWriter(chooser.getSelectedFile()+".txt");
edit.write(editedFileText.toString());
srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt");
srcFile.write(srcFileText.toString());
trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt");
trans.write(translFileText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}finally{
if(edit != null)
edit.close();
if(srcFile != null)
srcFile.close();
if(trans != null)
trans.close();
}
FileWriter writer=null;
try {
writer = new FileWriter(filename);
writer.write(sb.toString());
} catch (Exception e) {
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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();
}
}
}
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.