How to delete only the content of a file in Java? - 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.

Related

Trying to Continue the program when it returns file not found exception in java

I i am able to read the lines from csv and download the images from url when the url is not having the image it is showing file not found exception in middle of the program i want to continue the program with out terminating.
public static void main(String[] args) throws IOException {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
BufferedReader br = new BufferedReader(new FileReader("D:\\imgdwnld\\file.csv"));
String line = br.readLine();
while ((line = br.readLine()) !=null){
URL url = new URL(line);
inputStream = url.openStream();
outputStream = new FileOutputStream("D:\\imgdwnld\\" +
line.substring(line.lastIndexOf("/")));
byte[] buffer = new byte[2048];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
} catch (MalformedURLException e) {
System.out.println("MalformedURLException :- " + e.getMessage());
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException :- " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException :- " + e.getMessage());
} finally {
try {
inputStream.close();
outputStream.close();
} catch (IOException e) {
System.out.println("Finally IOException :- " + e.getMessage());
}
}
}
This is the relevant outline of your code:
try {
...
while ((line = br.readLine()) !=null) {
... process each CSV line ...
}
} catch (IOException e) {
... handle it ...
}
At the place where you catch the exception you have already broken out of the main loop. Change the code to have this outline:
while ((line = br.readLine()) !=null) {
try {
... process one CSV line ...
} catch (IOException e) {
... handle it, the loop will proceed with the next line
}
}
You need to remove the "return" instruction from the corresponding catch (or maybe from the whole code). In your case, the instruction allows to "exit" the main method so the rest of instruction (those after the return statement) won't be executed.
Another tip is to separate this instructions in blocs. For example, if reading the CSV and the Img are not bound, you may need to encapsulate each treatment in an individual try-catch block. When parsing/reading the CSV file fails, your code may continue fetching the image.

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

Can't read a file for strange reason [duplicate]

This question already has answers here:
Why I can't read a read only file?
(2 answers)
Closed 9 years ago.
I have these methods for reading and writing to a file:
/* Write content to a file */
private void writeToFile(ArrayList<String> list) {
File file = new File("jokesBody1.bjk");
FileOutputStream fos;
if(list != null){
try {
file.createNewFile();
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
file.createNewFile();
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject("");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* Read file's content */
private ArrayList<String> readFromFile() {
File file = new File("jokesBody1.bjk");
ArrayList<String> list = new ArrayList<String>();
try {
file.createNewFile();
ObjectInputStream ois = new ObjectInputStream( new FileInputStream( file ) );
try {
list = (ArrayList)ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
Log.e("log activity", "Can not read file: " + e.toString());
}
return list;
}
Everyrhing seems to be fine to me, but when I run the code I'm getting the following error:
02-15 17:02:07.655: E/log activity(1882): Can not read file: java.io.IOException: open failed: EROFS (Read-only file system)
Why the system is read only? Should I do something when I'm creating the file if it does not exist by file.createNewFile();?
I know that I'm missing something extremely small, but as a total beginner, I'm not able to spot it.
You get this error probably on Linux.
This file system is mounted as read-only.
So you cannot write to it.

java typing into file, file not showing, using bytes

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

Clearing File content in Internal Storage on Android

I have a logging class for writing into a file in the app's internal storage space. Whenever the log file exceeds the size limit. For clearing the contents, I am closing the current FileOutputStream and creating a new stream with Write mode and closing it. Is there a way better way for accomplishing this:
public final void clearLog() throws IOException {
synchronized (this) {
FileOutputStream fos = null;
try {
// close the current log file stream
mFileOutputStream.close();
// create a stream in write mode
fos = mContext.openFileOutput(
LOG_FILE_NAME, Context.MODE_PRIVATE);
fos.close();
// create a new log file in append mode
createLogFile();
} catch (IOException ex) {
Log.e(THIS_FILE,
"Failed to clear log file:" + ex.getMessage());
} finally {
if (fos != null) {
fos.close();
}
}
}
}
You could also overwrite your file with nothing.
UPDATE:
There seems to be a better option with getFilesDir () Have a look at this question How to delete internal storage file in android?
Write empty data into file:
String string1 = "";
FileOutputStream fos ;
try {
fos = new FileOutputStream("/sdcard/filename.txt", false);
FileWriter fWriter;
try {
fWriter = new FileWriter(fos.getFD());
fWriter.write(string1);
fWriter.flush();
fWriter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.getFD().sync();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
In this code:
fos = new FileOutputStream("/sdcard/filename.txt", false);
FALSE - for write new content. If TRUE - text append to existing file.
public void writetofile(String text){ // text is a string to be saved
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", false); //false will set the append mode to false
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(text);
outputWriter.close();
readfromfile();
Toast.makeText(getApplicationContext(), "file saved successfully",
Toast.LENGTH_LONG).show();
}catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources