Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*; // for Scanner class and a few other useful things
- import java.io.*; // to enable reading and writing from files
- public class FileIOExample {
- /* you need to include the "throws IOException" declaration
- * because things may go wrong with the file I/O process
- *
- * unless you want to use try-catch statements
- */
- public static void main(String[] args) throws IOException {
- // this line opens a Scanner to read from your input file
- // it reads just as if you were typing things into the console
- Scanner input = new Scanner(new File("input.txt"));
- // this next line creates a file and allows you to print to it
- // you use it like System.out.println()
- PrintWriter out = new PrintWriter(new File("output.txt"));
- // for instance, if you want to read in a list of integers from a file...
- List<Integer> list = new ArrayList<Integer>();
- while (input.hasNextInt()) {
- list.add(input.nextInt());
- }
- // then, if you want to sort the numbers and print it back out to your file...
- Collections.sort(list);
- for (Integer i : list) {
- out.println(i); // just like printing to console...! without the System
- }
- /* THESE NEXT TWO LINES ARE IMPORTANT... since you opened two files, one for reading and
- * one for writing, you have to close those files so that it releases the resources
- * back to your computer
- */
- input.close();
- out.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement