Java

Files in Java

Files in Java

This includes support for common operations like creating, reading from and writing to files; copy-pasting content between them; appending new information or deleting it completely - making these an ideal choice when dealing with complex file system tasks. 

The most important classes for working with files in Java are 

  • File: This class represents a file or directory on the file system. You can use it to perform operations such as creating, deleting, and renaming files. 
  • FileReader and FileWriter: These classes provide a way to read and write text data to a file.
  • InputStream and OutputStream: These classes provide a way to read and write binary data to a file. 

The following code creates a new file called "example.txt" and writes the text "Hello, World!" to it: 

File file = new File("example.txt"); 
FileWriter writer = new FileWriter(file); 
writer.write("Hello, World!"); 
writer.close(); 

Similarly, the following code reads the text from the file "example.txt" and prints it to the console: 

FileReader reader = new FileReader(file); 
int c; 
while((c = reader. read()) != -1) { 
System.out.print((char)c); 
} 
reader.close(); 
​​​​​​

It will print "Hello, World!" 
 

Top course recommendations for you

    Introduction to Application Security
    1 hrs
    Beginner
    4.2K+ Learners
    4.43  (365)
    Generics in Java
    1 hrs
    Beginner
    1.2K+ Learners
    Introduction to Spring Framework
    1 hrs
    Beginner
    2.8K+ Learners
    4.47  (260)
    Introduction to Appian
    2 hrs
    Beginner
    952 Learners
    4.32  (38)
    Introduction to Blue Prism
    1 hrs
    Beginner
    481 Learners
    4.63  (41)
    Fundamentals of UiPath
    1 hrs
    Beginner
    1K+ Learners
    4.58  (88)
    ASP.NET MVC Course for Beginners
    1 hrs
    Beginner
    4.4K+ Learners
    4.47  (212)
    Java Virtual Machine Introduction
    2 hrs
    Beginner
    1K+ Learners
    4.5  (58)