-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileService.java
More file actions
80 lines (73 loc) · 2.52 KB
/
FileService.java
File metadata and controls
80 lines (73 loc) · 2.52 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
77
78
79
80
import java.io.*;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class FileService
{
private final String FileName = "log.html";
private String FilePath = "./" + FileName;
private File File;
/**
* FileService constructor: Instantiates file
*/
public FileService()
{
File = new File(FilePath);
}
/**
* Reads all transactions from the file.
* @return A collection of transactions. If an error occurs, an empty collection is returned.
*/
public ArrayList<Double> ReadAllTransactions()
{
var transactions = new ArrayList<Double>();
try
{
var document = Jsoup.parse(File, "UTF-8");
var tableElements = SelectTable(document)
.select("tr")
.select("td");
for (Element td : tableElements)
{
var transactionText = td.text();
var transaction = Double.parseDouble(transactionText);
transactions.add(transaction);
}
} catch (Exception exception)
{
System.out.println("Unexpected error occured while reading transactions");
}
return transactions;
}
/**
* Adds a new transaction to the file. On error, notifies the user that the transaction may have not been saved
* @param transactionAmount Net monetary value of the new transaction
*/
public void AddTransaction(String transactionAmount)
{
try
{
var document = Jsoup.parse(File, "UTF-8");
var tableBody = SelectTable(document).select("tbody");
tableBody.append(String.format("<tr><td>%s</td></tr>", transactionAmount));
var bufferedWriter = new BufferedWriter(new FileWriter(File));
bufferedWriter.write(document.toString());
bufferedWriter.close();
} catch (Exception exception)
{
System.out.println("Unexpected error occured while saving transaction. Transaction may not have been saved.");
}
}
/**
* Retrieves the transactions table from the given document
* @param document Document to query for the transactions table
* @return The html table element for the table of transactions
*/
private Element SelectTable(Document document)
{
return document.getElementById("transactions");
}
}