-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMyFile.java
76 lines (65 loc) · 2.15 KB
/
MyFile.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MyFile
{
public static void FileWriteOperation()
{
try{
FileWriter fileWriteObj = new FileWriter("file1.txt");
fileWriteObj.write("Hello, I'm John Doe Studying in Shri K.J Polytechnic Bharuch.");
System.out.println("Successfully Written.");
fileWriteObj.close();
}
catch(IOException e){
System.out.println("Any Error occured.");
}
}
public static void FileReadOperation()
{
try{
File fileObj = new File("file1.txt");
Scanner fileReadobj = new Scanner(fileObj);
while(fileReadobj.hasNextLine()){
String data = fileReadobj.nextLine();
System.out.println(data);
}
fileReadobj.close();
}
catch(IOException e){
System.out.println("Any Error occured.");
}
}
public static void FileDeleteOperation(){
String strToFind = "Shri";
String strToReplace = "Shree";
try{
File fileRead = new File("file1.txt");
Scanner fread = new Scanner(fileRead);
File fileWrite = new File("tempfile.txt");
FileWriter fout = new FileWriter(fileWrite,true);
while(fread.hasNextLine()){
String str = fread.nextLine();
str = str.replaceFirst(strToFind, strToReplace);
fout.write(str);
}
String fileName = fileRead.getPath();
fileRead.delete();
if(fileWrite.renameTo(new File(fileName)))
System.out.println("Delete Success");
else
System.out.println("Delete Not Success");
fread.close();
fout.close();
}catch(IOException e){
System.out.println("Any Error occured.");
}
}
public static void main(String args[])
{
// FileReadOperation();
// FileWriteOperation();
FileDeleteOperation();
}
}