0% found this document useful (0 votes)
41 views25 pages

ANWESHA MONDAL - MCAN - 293 - Java Assignment4

The documents describe examples of reading and writing files in Java using FileWriter, FileReader, BufferedReader, and Scanner classes. The examples write text to files, read files line-by-line and character-by-character, count words and lines in a file, calculate word frequencies, and search a file for patterns. Overall the documents provide several code examples for performing common file I/O operations in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views25 pages

ANWESHA MONDAL - MCAN - 293 - Java Assignment4

The documents describe examples of reading and writing files in Java using FileWriter, FileReader, BufferedReader, and Scanner classes. The examples write text to files, read files line-by-line and character-by-character, count words and lines in a file, calculate word frequencies, and search a file for patterns. Overall the documents provide several code examples for performing common file I/O operations in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

1.

code: -
javaapplication11:-
FileWriteExample:

import java.io.FileWriter;
import
java.io.IOException;

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author DELL
*/
public class FileWriteExample {
public static void main(String[] args) {
String fileName = "C:\\File\\
File4.txt";
try (FileWriter writer = new FileWriter(fileName)) {
writer.write("Object Oriented Programming world.\n");
writer.write("Java is Object Oriented Programming Language.\n");
writer.write("Java is Platform independent language\n");
writer.write("Java supports Multithreading. Java virtual machine is
important.");
System.out.println("File written successfully.");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}
}

Output: -

File view:

2. code:-
javaapplication16:-
counts.java:

import java.util.Scanner;

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author DELL
*/
public class counts {

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{ String input;
try ( // TODO code application logic here
Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter a string: ");
input = scanner.nextLine();
}

int wordCount = countWords(input);


System.out.println("The string \"" + input + "\" has " + wordCount + "
words.");
}

public static int countWords(String str)


{ if (str == null || str.isEmpty()) {
return 0;
}

String[] words = str.split("\\


s+"); return words.length;
}
}

Output:
3. code:-
javaapplication10:-
FileReaderExample:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {


public static void main(String[] args)
{ String fileName;
fileName = "D:\\File\\File4.txt";
try (BufferedReader reader = new BufferedReader(new
FileReader(fileName))) {
int character;
while ((character = reader.read()) != -1)
{ System.out.print((char) character);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}

Text file:
Output:

4. code:-
javaapplication10:-
FileReaderExample:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {


public static void main(String[] args)
{ String fileName;
fileName = "D:\\File\\File4.txt";
try (BufferedReader reader = new BufferedReader(new
FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null)
{ System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}

Output:-

5. code:-
javaApplication1
0:
FileReaderExample:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author DELL
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class FileWordCounter {
private String
fileName;

public FileWordCounter(String fileName) {


this.fileName = fileName;
}

public int countWords()


{ int totalWords = 0;
try (BufferedReader reader = new BufferedReader(new
FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null)
{ String[] words = line.split(" ");
totalWords += words.length;
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
return totalWords;
}

public int countLines()


{ int totalLines = 0;
try (BufferedReader reader = new BufferedReader(new
FileReader(fileName))) {
while (reader.readLine() != null)
{ totalLines++;
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
return totalLines;
}
}

public class FileReaderExample {


public static void main(String[] args) {
String fileName = "D:\\File\\
File4.txt";
FileWordCounter counter = new
FileWordCounter(fileName); int totalWords =
counter.countWords();
int totalLines = counter.countLines();
System.out.println("Total words: " + totalWords);
System.out.println("Total lines: " + totalLines);
}
}

Output:

6. code:-

javaApplication10:
FileReaderExample:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author DELL
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

class FileWordFrequencyCounter {
private final String fileName;

public FileWordFrequencyCounter(String fileName)


{ this.fileName = fileName;
}

public Map<String, Integer> countWordFrequency() {


Map<String, Integer> wordFrequencyMap = new
HashMap<>();
try (BufferedReader reader = new BufferedReader(new
FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null)
{ String[] words = line.split(" ");
for (String word : words) {
String cleanedWord = word.toLowerCase().replaceAll("[^a-z0-9]",
"");
if (cleanedWord.isEmpty())
{ continue;
}
int frequency = wordFrequencyMap.getOrDefault(cleanedWord,
0)
;
wordFrequencyMap.put(cleanedWord, frequency + 1);
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
return wordFrequencyMap;
}
}

public class FileReaderExample {


public static void main(String[] args) {
String fileName = "D:\\File\\
File4.txt";
FileWordFrequencyCounter counter = new
FileWordFrequencyCounter(fileName);
Map<String, Integer> wordFrequencyMap
= counter.countWordFrequency();
wordFrequencyMap.entrySet().forEach((entry) -> {
System.out.println(entry.getKey() + " : " + entry.getValue());
});
}
}

Output:-
7. code:-
javaApplication11:
FileReaderExample:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author DELL
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class FilePatternSearcher
{ private String
fileName;

public FilePatternSearcher(String fileName)


{ this.fileName = fileName;
}

public void searchPattern(String pattern) {


List<Integer> lineNumbers = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new
FileReader(fileName))) {
String line;
int lineNumber = 1;
while ((line = reader.readLine()) != null)
{ if (line.contains(pattern)) {
lineNumbers.add(lineNumber);
int index = line.indexOf(pattern);
while (index >= 0) {
System.out.printf("Line %d, Position %d%n", lineNumber, index
+
1);
index = line.indexOf(pattern, index + 1);
}
}
lineNumber++;
}
System.out.printf("Total occurrences of '%s': %d%n", pattern,
lineNumbers.size());
System.out.printf("Line numbers where '%s' exists: %s%n", pattern,
lineNumbers.toString());
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}

public class FileReaderExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a pattern to search: ");
String pattern = scanner.nextLine().trim();
String fileName = "C:\\File\\File4.txt";
FilePatternSearcher searcher = new FilePatternSearcher(fileName);
searcher.searchPattern(pattern);
}
}

Output:

8. code:-
javaApplication1
1:
FileScannerExample:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author DELL
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import
java.io.IOException;

public class FileScannerExample {


public static void main(String[] args)
{
String folderPath = "C://File"; // replace with the path of the folder you want
to scan
File folder = new File(folderPath);
File[] files = folder.listFiles((dir, name) -> name.endsWith(".txt") ||
name.endsWith(".TXT"));
int fileCount = files.length;
System.out.println("Number of .txt or .TXT files: " + fileCount);

for (File file : files) {


try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
System.out.println("Contents of " + file.getName() + ":");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading file " + file.getName() + ": "
+ e.getMessage());
}
}
}
}

Output:

9. code:
javaApplication11:
FileCopyExample:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author DELL
*/
import java.io.FileReader;
import java.io.FileWriter;
import
java.io.IOException;

public class FileCopyExample {


public static void main(String[] args) {
String sourceFile = "C:\\File\\File4.txt";
String destinationFile = "C:\\File\\File6.txt";
try (FileReader reader = new FileReader(sourceFile);
FileWriter writer = new FileWriter(destinationFile)) {
int c;
while ((c = reader.read()) != -1)
{ writer.write(c);
}
System.out.println("File copied successfully.");
} catch (IOException e) {
System.err.println("Error copying file: " + e.getMessage());
}
}
}

Output:
10. code:-
javaApplication11:
student.java:
import java.io.*;
import java.util.ArrayList;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author DELL
*/
public class Student implements Serializable
{ private final String name;
private final int rollNumber;
private final int marks;
private final String year;

public Student(String name, int rollNumber, int marks, String year) {


this.name = name;
this.rollNumber =
rollNumber; this.marks =
marks;
this.year = year;
}

public String getName()


{ return name;
}

public int getRollNumber()


{ return rollNumber;
}

public int getMarks()


{ return marks;
}

public String getYear()


{ return year;
}

@Override
public String toString() {
return "Name: " + name + ", Roll Number: " + rollNumber + ", Marks: " + marks
+ ", Year: " + year;
}
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Asutosh", 1001, 85, "2022"));
students.add(new Student("Bikash", 1002, 92, "2022"));
students.add(new Student("Chaaru", 1003, 78, "2023"));
students.add(new Student("Damini", 1004, 90, "2023"));
students.add(new Student("Eshani", 1005, 80, "2024"));

String fileName = "C:\\File\\file8.txt";


try (ObjectOutputStream outputStream = new ObjectOutputStream(new
FileOutputStream(fileName))) {
for (Student student : students) {
outputStream.writeObject(student);
}
System.out.println("Students written to file successfully.");
} catch (IOException e) {
System.err.println("Error writing students to file: " + e.getMessage());
}

try (ObjectInputStream inputStream = new ObjectInputStream(new


FileInputStream(fileName))) {
System.out.println("Students read from file:");
while (true) {
try {
Student student = (Student) inputStream.readObject();
System.out.println(student.toString());
} catch (EOFException e) {
break; // reached end of file
}
}
} catch (IOException | ClassNotFoundException e) {
System.err.println("Error reading students from file: " + e.getMessage());
}
}
}

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy