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
    2.2K+ Learners
    4.54  (114)
    Generics in Java
    1 hrs
    Beginner
    686 Learners
    Introduction to Spring Framework
    1 hrs
    Beginner
    1.7K+ Learners
    Introduction to Software Development Security
    2 hrs
    Beginner
    3K+ Learners
    Introduction to Appian
    2 hrs
    Beginner
    753 Learners
    4.41  (27)
    Introduction to Blue Prism
    1 hrs
    Beginner
    344 Learners
    4.6  (20)
    Introduction to Apache Pig
    2 hrs
    Beginner
    215 Learners
    Fundamentals of UiPath
    1 hrs
    Beginner
    663 Learners
    4.49  (37)
    ASP.NET MVC Course for Beginners
    1 hrs
    Beginner
    3.5K+ Learners
    4.6  (125)
    Java Virtual Machine Introduction
    2 hrs
    Beginner
    708 Learners
    4.68  (25)