Download presentation
Presentation is loading. Please wait.
1
Files – part 2 Alexandra Stefan
2
File Operations Read from file Write to file Close a file
Open for reading Read Process line: String.split Write to file Open for writing Write Close a file
3
Other File Operations File path Create a directory
Local, Absolute, Relative File path separator It depends on the operating system Do not hardcode it. Get the one for the system you are running on. Create a directory Delete a file or a directory List directories Useful: System, System.getProperty(…) File:
4
File Path File path separator - Do not hardcode.
Unix: / , Windows: \ (\ as a string will be: "\\") Get the one for the system you are running using either: String sep = File.separator; //or: String sep = System.getProperty("file.separator"); // sep will be "\\" or "/" Build a file path - String concatenation String fPath = ".." + sep + "data1.txt" //fPath:..\data1.txt or ../data1.txt String dirName = System.getProperty("user.home"); String fPath2 = dirName + sep + "datasets" + sep + "data1.txt" // fPath2 is: C:\Users\alex\datasets\data1.txt // Actual string "C:\\Users\\alex\\datasets\\data1.txt" File path Example Description Local data1.txt Looks in the current project folder. Absolute C:\Users\alex\courses\1310\data1.txt Complete path name. Do not use it! Relative:up down ..\data1.txt hw3\data1.txt Move ‘up’ or ‘down’ from the current folder. USEFUL.
5
Directory and Other Create File object:
File f = new File(parentDirName, "newDir"); Create a directory: f.mkdir(), f.mkdirs() Delete a directory: f.delete() List content of the directory: f.list() Other: f.exists() f.isDirectory(), f.isFile() f.lastModified() File:
6
System Properties Get them using: Examples:
System.getProperty( propertyStr ); Examples: Line separators (for new line) File name separators, User’s working and home directories See:
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.