1
+ import java .io .*;
2
+ import java .nio .file .*;
3
+ import java .util .List ;
4
+
5
+ public class FileProcessingCheatSheet {
6
+ public static void main (String [] args ) throws IOException {
7
+ // Come up with the whole way to write text to a file, read from a file, manipulate path names, etc.
8
+ // There are lots of way to do this. Do I want to touch on all of them? Pick one and run with it?
9
+ // Remember, there was an issue in clipboard where it wasn't reading files with newlines as you would expect (platform independent newlines)
10
+
11
+ // FileReader/Writer are basic and only support writing characters and streams
12
+ // Wrapping FileReader/Writer in BufferedReader/Writer adds buffering and line-oriented operations
13
+
14
+ // basic
15
+ // PrintWriter is similar to System.out
16
+ PrintWriter w = new PrintWriter ("test_data.txt" ); // could also use a BufferedWriter
17
+ w .println ("line one" ); // OS-independent line separator
18
+ w .printf ("line %d%n" , 2 ); // %n = OS-independent line separator
19
+ w .println ("line three" );
20
+ w .close ();
21
+
22
+ BufferedReader i = new BufferedReader (new FileReader ("test_data.txt" ));
23
+ String line ;
24
+ while ((line = i .readLine ()) != null ) { // .readline() consumes line terminator
25
+ System .out .println ("READ: " + line );
26
+ }
27
+ i .close ();
28
+
29
+ // console (simple prompts for input)
30
+ // (also see InputCheatSheet)
31
+ Console c = System .console ();
32
+ if (c == null ) {
33
+ System .out .println ("No console. Skipping consle sample code." );
34
+ } else {
35
+ String inp = c .readLine ("Enter text here Mr. %s" , "Smith" ); // Can be string literal, or empty for no prompt
36
+ System .out .println ("Entered: " + inp );
37
+ }
38
+
39
+ // write to a file (write vs append)
40
+ PrintWriter appending = new PrintWriter (new FileWriter ("test_data.txt" , true ));
41
+ appending .println ("New line appended" ); // uses OS-independent line separator
42
+ appending .printf ("another line%n" ); // %n - OS-independent line separator
43
+ appending .println ("final line" );
44
+ appending .close ();
45
+
46
+ // Note: java.io is older (From Java 1.4) where java.nio is newer
47
+ // - can use File.toPath() to convert from "old" to "new"
48
+ // - java.nio.file.Path = core of file processing in Java
49
+ // - java.nio.file.Path replaces java.io.File (from Java 1.7)
50
+ // - file or directory corresponding to the Path might not exist
51
+ // - operate on path itself and don't access filesystem
52
+ // - Paths is a Path helper class
53
+ // - java.nio.file.Files
54
+ // - static methods that take Path's to read, write, and manipulate files and directories on filesystems.
55
+ Path p1 = Paths .get ("c:\\ abc\\ def" );
56
+ System .out .println (p1 );
57
+ // Path p1b = Paths.get("aa", "bb", "cc", "dd"); // relative path
58
+ Path p1b = Paths .get ("aa\\ bb\\ cc\\ dd" ); // relative path
59
+ System .out .println (p1b .toAbsolutePath ());
60
+ Path p2 = Paths .get ("\\ aa\\ bb\\ cc\\ dd" );
61
+ System .out .println (p2 );
62
+ System .out .println (p2 .toString ());
63
+ System .out .println (p2 .getFileName ());
64
+ System .out .println (p2 .getParent ());
65
+ System .out .println (p2 .getRoot ()); // null if a relative path
66
+ System .out .println (p2 .getNameCount ());
67
+ System .out .println (p2 .getName (0 ));
68
+ System .out .println (p2 .subpath (1 , 3 ));
69
+ System .out .println (p2 .toUri ());
70
+ System .out .println (p2 .resolve ("ee.txt" )); // joining two Paths
71
+ System .out .println (p2 .resolve (Paths .get ("yy\\ zz" ))); // joining two Paths
72
+ System .out .println (Paths .get ("home" ).relativize (Paths .get ("home\\ sally\\ bar" ))); // Result: sally\bar
73
+ p1 .equals (p2 );
74
+ p1 .startsWith (p2 );
75
+ p1 .endsWith (p2 );
76
+ for (Path path_name : p2 ) {
77
+ System .out .println ("Path: " + path_name );
78
+ }
79
+ //
80
+ Path tmp = Paths .get ("test_data.txt" );
81
+ Files .exists (tmp );
82
+ Files .notExists (tmp );
83
+ Files .isReadable (tmp );
84
+ Files .isWritable (tmp );
85
+ Files .isExecutable (tmp );
86
+ Files .size (tmp );
87
+ Files .isDirectory (tmp );
88
+ Files .isRegularFile (tmp );
89
+ // Files.getLastModifiedTime(tmp);
90
+ // Files.setLastModifiedTime(tmp, FileTime.from(10000L, TimeUnit.DAYS));
91
+
92
+ // read lines from a file
93
+ List <String > lines = Files .readAllLines (tmp );
94
+ for (String s : lines ) {
95
+ System .out .println ("_" + s + "_" );
96
+ }
97
+
98
+ // stream interface to read lines from a file
99
+ Files .lines (tmp )
100
+ .filter (s -> s .startsWith ("line" ))
101
+ .forEach (s -> System .out .println ("*" + s + "*" ));
102
+
103
+ Path tmp2 = Paths .get ("temp2.txt" );
104
+ Path tmp3 = Paths .get ("temp3.txt" );
105
+ Files .copy (tmp , tmp2 );
106
+ Files .move (tmp2 , tmp3 );
107
+ Files .delete (tmp3 );
108
+
109
+ Files .createDirectory (Paths .get ("mytempdir" ));
110
+ Files .delete (Paths .get ("mytempdir" ));
111
+
112
+ // iterate over root directories in filesystem
113
+ Iterable <Path > dirs = FileSystems .getDefault ().getRootDirectories ();
114
+ for (Path p : dirs ) {
115
+ System .out .println (p );
116
+ }
117
+
118
+ // iterate over directory
119
+ try (DirectoryStream <Path > stream = Files .newDirectoryStream (Paths .get ("src" ))) {
120
+ for (Path file : stream ) {
121
+ System .out .println ("In src: " + file .getFileName ());
122
+ }
123
+ }
124
+ // iterate over directory with glob matching
125
+ try (DirectoryStream <Path > stream = Files .newDirectoryStream (Paths .get ("src" ), "*.java" )) {
126
+ for (Path entry : stream ) {
127
+ System .out .println ("Glob: " + entry .getFileName ());
128
+ }
129
+ }
130
+ }
131
+ }
132
+
133
+
134
+ /* IS THERE ANYTHING USEFUL IN HERE? I DELETED THIS FILE...
135
+ # Java File IO Cheat Sheet
136
+
137
+ ### Read text from a file
138
+
139
+ Files.readAllBytes()
140
+
141
+ File file = new File("mypath/myfile.txt");
142
+ String dat = new String(Files.readAllBytes(file.toPath()));
143
+
144
+ Scanner
145
+
146
+ Scanner in = new Scanner(Paths.get("stuff.txt"));
147
+ while (in.hasNextLine()) {
148
+ System.out.println("LINE:" + in.nextLine());
149
+ }
150
+
151
+
152
+ ### Write text to a file
153
+
154
+ Print Writer
155
+
156
+ PrintWriter out = new PrintWriter("stuff.txt");
157
+ out.print("word");
158
+ out.println("line");
159
+ out.printf("f: %s %d\n", "hello", 42);
160
+ out.close();
161
+
162
+ */
0 commit comments