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.1K+ Learners
    4.42  (351)
    Generics in Java
    1 hrs
    Beginner
    1.1K+ Learners
    Introduction to Spring Framework
    1 hrs
    Beginner
    2.6K+ Learners
    4.33  (160)
    Introduction to Appian
    2 hrs
    Beginner
    937 Learners
    4.32  (38)
    Introduction to Blue Prism
    1 hrs
    Beginner
    467 Learners
    4.63  (38)
    Fundamentals of UiPath
    1 hrs
    Beginner
    1K+ Learners
    4.56  (78)
    ASP.NET MVC Course for Beginners
    1 hrs
    Beginner
    4.4K+ Learners
    4.47  (205)
    Java Virtual Machine Introduction
    2 hrs
    Beginner
    987 Learners
    4.49  (57)