-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileWriterAdvanced.java
More file actions
76 lines (67 loc) · 2.6 KB
/
FileWriterAdvanced.java
File metadata and controls
76 lines (67 loc) · 2.6 KB
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.util.Scanner;
import java.io.FileWriter;
class FileWriterAdvanced{
public String[] dataToWrite = new String[10]; //declaring fixed size global array
public static void main(String[] args){
FileWriterAdvanced object = new FileWriterAdvanced(); //creating a new instance of our class
object.start(); //calling start function inside the instance
}
public void start(){
try{//try and catch block to catch any potential errors
Scanner scanner = new Scanner(System.in);
this.inputLinesFromUser(scanner); //calling a function that fills the array
this.writeLines(this.inputFileNameFromUser(scanner));
scanner.close();
}catch(Exception e){ //error handling
System.out.println("An error happend while writing to file: ");
e.printStackTrace();
}
}
/*
* The following function accepts the Scanner object as a parameter
* and reads line to the array from this Scanner
*/
public void inputLinesFromUser(Scanner scanner){
int count = 0;
String line;
do{//readlines until user types in "STOP" or until the array is full
System.out.print("Enter line or type \"STOP\" to stop writing: ");
line = scanner.nextLine();
if(line.equals("STOP")){
break;
}
this.dataToWrite[count] = line; //storing line in the global array
count++;
}while(this.canWriteToArray(count));
}
/*
* The following function returns a bool value that represents if the global array is full or not
*/
public boolean canWriteToArray(int index){
return index < this.dataToWrite.length;
}
/*
* The following function accepts Scanner object as a parameter, reads file name from this Scanner
* instance and returns file name as a String object
*/
public String inputFileNameFromUser(Scanner scanner){
System.out.print("Enter the name of file: ");
return scanner.nextLine();
}
/*
* The following function accepts the file name as a parameter and writes data from the global array to the file given
*/
public void writeLines(String file){
try{//try catch block to catch any potential errors
FileWriter fileWriter = new FileWriter(file);
for(int i = 0; i < this.dataToWrite.length; i++){
fileWriter.write(this.dataToWrite[i] + "\n"); //writing each element of the array on separate lines of the file
}
fileWriter.close();
System.out.println("Done!");
}catch(Exception e){//error handling
System.out.println("An error happend while writing to file: ");
e.printStackTrace();
}
}
}