How do I create a file and write to it?

Note that each of the code samples below may throw IOException. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling. Note that each of the code samples below will overwrite the file if it already exists Creating a text file: PrintWriter writer = new PrintWriter(“the-file-name.txt”, “UTF-8”); writer.println(“The first line”); writer.println(“The second line”); … Read more

Reading a plain text file in Java

ASCII is a TEXT file so you would use Readers for reading. Java also supports reading from a binary file using InputStreams. If the files being read are huge then you would want to use a BufferedReader on top of a FileReader to improve read performance. Go through this article on how to use a Reader I’d also recommend you download and read this wonderful … Read more

java.io.FileNotFoundException: the system cannot find the file specified

Put the word.txt directly as a child of the project root folder and a peer of src Project_Root src word.txt Disclaimer: I’d like to explain why this works for this particular case and why it may not work for others. Why it works: When you use File or any of the other FileXxx variants, you are looking for a file … Read more

How do I save a String to a text file using Java?

If you’re simply outputting text, rather than any binary data, the following will work: PrintWriter out = new PrintWriter(“filename.txt”); Then, write your String to it, just like you would to any output stream: You’ll need exception handling, as ever. Be sure to call out.close() when you’ve finished writing. If you are using Java 7 or later, you … Read more

Java read file and store text in an array

Stored as strings: public class ReadTemps { public static void main(String[] args) throws IOException { // TODO code application logic here // // read KeyWestTemp.txt // create token1 String token1 = “”; // for-each loop for calculating heat index of May – October // create Scanner inFile1 Scanner inFile1 = new Scanner(new File(“KeyWestTemp.txt”)).useDelimiter(“,\\s*”); // Original … Read more