- Как удалить содержимое файла, используя класс FileOutputStream в Java?
- 4 ответа
- Delete the Contents of a File in Java
- 1. Introduction
- 2. Using PrintWriter
- 3. Using FileWriter
- 4. Using FileOutputStream
- 5. Using Apache Commons IO FileUtils
- 6. Using Java NIO Files
- 7. Using Java NIO FileChannel
- 8. Using Guava
- 9. Conclusion
- How to Delete the Contents of a File
- Java — Как очистить текстовый файл, не удаляя его?
- 4 ответа
Как удалить содержимое файла, используя класс FileOutputStream в Java?
Я работаю с классом FileOutputStream в Java, но я не знаю, как удалить «содержимое» файла (основная причина, по которой мне нужно перезаписать файл).
4 ответа
Если вы хотите удалить содержимое файла, но не сам файл, вы можете сделать:
PrintWriter pw = new PrintWriter("file.txt"); pw.close();
Несколько секунд Googling дали мне это:
Чтобы полностью удалить файл, выполните:
File file = new File("file.txt"); f.delete();
Основная причина, по которой мне нужно перезаписать файл.
Один из способов сделать это — удалить файл, используя File.delete() или же Files.delete(Path) , Последнее предпочтительнее, так как может сказать, почему удаление не удалось.
Другой способ — просто открыть файл для записи. При условии, что вы не открываете в режиме «добавления», открытие файла для записи обрезает файл до нуля байтов.
Обратите внимание, что есть тонкое различие в поведении этих двух подходов. Если вы удалите файл, а затем создадите новый, любое другое приложение с таким же открытым файлом не заметит. Напротив, если вы усекаете файл, то другие приложения с открытым файлом будут наблюдать эффекты усечения при чтении.
На самом деле, это зависит от платформы. На некоторых платформах Java-приложение, которое пытается открыть файл для чтения, который другой файл имеет для записи, получит исключение.
Delete the Contents of a File in Java
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Introduction
In this tutorial, we’ll see how we use Java to delete the contents of a file without deleting the file itself. Since there are many simple ways to do it, let’s explore each one by one.
2. Using PrintWriter
Java’s PrintWriter class extends the Writer class. It prints the formatted representation of objects to the text-output stream.
We’ll perform a simple test. Let’s create a PrintWriter instance pointing to an existing file, deleting existing content of the file by just closing it, and then make sure the file length is empty:
new PrintWriter(FILE_PATH).close(); assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
Also, note that if we don’t need the PrintWriter object for further processing, this is the best option. However, if we need the PrintWriter object for further file operations, we can do this differently:
PrintWriter writer = new PrintWriter(FILE_PATH); writer.print(""); // other operations writer.close();
3. Using FileWriter
Java’s FileWriter is a standard Java IO API class that provides methods to write character-oriented data to a file.
Let’s now see how we can do the same operation using FileWriter:
new FileWriter(FILE_PATH, false).close();
Similarly, if we need the FileWriter object for further processing, we can assign it to a variable and update with an empty string.
4. Using FileOutputStream
Java’s FileOutputStream is an output stream used for writing byte data to a file.
Now, let’s delete the content of the file using FileOutputStream:
new FileOutputStream(FILE_PATH).close();
5. Using Apache Commons IO FileUtils
Apache Commons IO is a library that contains utility classes to help out with common IO problems. We can delete the content of the file using one of its utility classes – FileUtils.
To see how this works, let’s add the Apache Commons IO dependency to our pom.xml:
After that, let’s take a quick example demonstrating deletion of file content:
FileUtils.write(new File(FILE_PATH), "", Charset.defaultCharset());
6. Using Java NIO Files
Java NIO File was introduced in JDK 7. It defines interfaces and classes to access files, file attributes, and file systems.
We can also delete the file contents using java.nio.file.Files:
BufferedWriter writer = Files.newBufferedWriter(Paths.get(FILE_PATH)); writer.write(""); writer.flush();
7. Using Java NIO FileChannel
Java NIO FileChannel is NIO’s implementation to connect a file. It also complements the standard Java IO package.
We can also delete the file contents using java.nio.channels.FileChannel:
FileChannel.open(Paths.get(FILE_PATH), StandardOpenOption.WRITE).truncate(0).close();
8. Using Guava
Guava is an open source Java-based library that provides utility methods to do I/O operations. Let’s see how to use the Guava API for deleting the file contents.
First, we need to add the Guava dependency in our pom.xml:
com.google.guava guava 31.0.1-jre
After that, let’s see a quick example to delete file contents using Guava:
File file = new File(FILE_PATH); byte[] empty = new byte[0]; com.google.common.io.Files.write(empty, file);
9. Conclusion
To summarize, we’ve seen multiple ways to delete the content of a file without deleting the file itself.
The full implementation of this tutorial can be found over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
How to Delete the Contents of a File
Learn to delete or clear the content of a file without deleting the file using standard IO classes and 3rd party libraries.
1. Using PrintWriter Constructor
The PrintWiter is used to write formatted strings to a text output stream.
The PrintWriter(file) constructor creates a new PrintWriter with the specified file parameter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created.
File file = new File("/path/file"); try(PrintWriter pw = new PrintWriter(file)) < //Any more operations if required >catch (FileNotFoundException e)
2. Using FileWriter Constructor
The FileWeite is also used to write text to character files. Similar to PrintWriter, the constructor of the FileWriter also empties the file if the file is not been opened for the append operation.
In the given example, the second parameter false indicates the append mode. If it is true then bytes will be written to the end of the file rather than the beginning.
File file = new File("/path/file"); try(FileWriter fw = new FileWriter(file)) < //Any more operations if required >catch (IOException e)
A random-access file behaves like a large array of bytes stored in the file system. We can use its setLength() method to empty the file.
try(RandomAccessFile raf = new RandomAccessFile(file, "rw")) < raf.setLength(0); >catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e)
4. Using NIO’s Files.newBufferedWriter()
We can also use the BufferedWriter to write an empty string into the file. This will make the file size zero by deleting all the content of it.
try(BufferedWriter writer = Files.newBufferedWriter(file.toPath())) < writer.write(""); writer.flush(); >catch (IOException e)
5. Using Commons IO FileUtils
The FileUtils class be used to write the empty string into the file that effectively deletes all the content present in the file.
File file = new File("/path/file"); try < FileUtils.write(file, "", StandardCharsets.UTF_8); >catch (IOException e)
Include the latest version of Commons IO library from Maven.
In this Java tutorial, we learned to make the file empty by deleting all the content in it. This makes the file size zero without deleting the file itself.
We learned to use the Java IO’s PrintWriter, FileWriter, NIO’s Files class and Commons IO’s FileUtils class for emptying the file.
Java — Как очистить текстовый файл, не удаляя его?
если их уже нет. Но что, если один существует, и я хочу его очищать каждый раз, когда я запускаю программу? Это то, что мне интересно: повторить еще раз, как очистить файл, который уже существует, чтобы быть пустым? Вот что я думал:
4 ответа
Если вы хотите очистить файл без удаления, возможно, вы можете обойти это
public static void clearTheFile()
Изменение: это исключает исключение, поэтому нужно поймать исключения
Вы уверены, что метод flush очищает содержимое файла? Я думал, что flush просто убедится, что поток полностью опустошен ..
FileWriter во второй строке выдает исключение io, есть что-то, что нужно изменить, а не просто выбрасывает IOException после clearFile ()?
Лучше всего я мог подумать:
Files.newBufferedWriter(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
Files.newInputStream(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
В обоих случаях, если файл, указанный в pathObject, доступен для записи, то этот файл будет усечен. Не нужно вызывать функцию write(). Выше кода достаточно, чтобы удалить/усечь файл. Это новое в java 8.
Вы можете удалить файл и создать его снова, а не делать много io.
Кроме того, вы можете просто перезаписать содержимое файла за один раз, как объяснено в других ответах:
PrintWriter writer = new PrintWriter(file); writer.print(""); writer.close();
Кроме того, вы используете конструктор из Scanner который принимает аргумент String . Этот конструктор не будет читать из файла, но использовать аргумент String в качестве текста для сканирования. Сначала вы должны создать дескриптор файла, а затем передать его конструктору Scanner :
File file = new File("jibberish.txt"); Scanner scanner = new Scanner(file);