Java transfer content from one file to another
Why transfer content from one file to another?
When we do analysis on content in files, we may need to read content from one file and do various kinds of processing (e.g. exclude/add/modify some parts), and then output results to another file. This process occurs very often if you do simple program analysis or file content analysis.
This is the java code quick reference. It simply read the input file line by line, and then output each line to the other file. You can simply copy the code and use it in your project.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { File dir = new File("."); String source = dir.getCanonicalPath() + File.separator + "Code.txt"; String dest = dir.getCanonicalPath() + File.separator + "Dest.txt"; File fin = new File(source); FileInputStream fis = new FileInputStream(fin); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); FileWriter fstream = new FileWriter(dest, true); BufferedWriter out = new BufferedWriter(fstream); String aLine = null; while ((aLine = in.readLine()) != null) { //Process each line and add output to Dest.txt file out.write(aLine); out.newLine(); } // do not forget to close the buffer reader in.close(); // close buffer writer out.close(); } } |
Note: Do not forget to close the input/output stream to prevent memory problems.
Result Screenshot
<pre><code> String foo = "bar"; </code></pre>
-
Thippani Vamshi
-
aditya pawar
-
Matthew Arrivel
-
Willem Meijer
-
Guest