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.5K+ Learners
    4.43  (423)
    Generics in Java
    1 hrs
    Beginner
    1.2K+ Learners
    Introduction to Spring Framework
    1 hrs
    Beginner
    2.9K+ Learners
    4.49  (290)
    Introduction to Appian
    2 hrs
    Beginner
    977 Learners
    4.38  (48)
    Introduction to Blue Prism
    1 hrs
    Beginner
    499 Learners
    4.65  (51)
    Fundamentals of UiPath
    1 hrs
    Beginner
    1.1K+ Learners
    4.63  (108)
    ASP.NET MVC Course for Beginners
    1 hrs
    Beginner
    4.5K+ Learners
    4.47  (222)
    Java Virtual Machine Introduction
    2 hrs
    Beginner
    1K+ Learners
    4.5  (64)