VL-Programmieren/VL12/Aufgabe01/StringFeld.java

75 lines
1.8 KiB
Java
Raw Normal View History

2024-05-01 21:38:01 +00:00
package VL12.Aufgabe01;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
* A field to store some information.
2024-05-06 20:19:27 +00:00
*
2024-05-01 21:38:01 +00:00
* @author Sebastian Brosch
*/
class StringFeld {
private String[] values;
StringFeld(String filePath) {
List<String> lines = getFileLines(filePath);
this.values = new String[lines.size()];
lines.toArray(this.values);
}
StringFeld(String filePath, String separator, int index) {
List<String> lines = getFileLines(filePath);
this.values = new String[lines.size()];
2024-05-06 20:19:27 +00:00
for (int i = 0; i < lines.size(); i++) {
2024-05-01 21:38:01 +00:00
this.values[i] = lines.get(i).split(separator)[index];
}
}
/**
* Method to get a value.
2024-05-06 20:19:27 +00:00
*
2024-05-01 21:38:01 +00:00
* @param index The index of the value.
* @return The value of the given index.
*/
public String get(int index) {
index = index % this.values.length;
return this.values[index];
}
/**
* Method to get a value.
2024-05-06 20:19:27 +00:00
*
* @param index The index of the value.
2024-05-01 21:38:01 +00:00
* @param maxLength The max length of the value.
* @return The value of the given index.
*/
public String get(int index, int maxLength) {
index = index % this.values.length;
2024-05-06 20:19:27 +00:00
if (this.values[index].length() > maxLength) {
2024-05-01 21:38:01 +00:00
return this.values[index].substring(0, maxLength);
} else {
return this.values[index];
}
}
/**
* Method to get all the lines of a file.
2024-05-06 20:19:27 +00:00
*
2024-05-01 21:38:01 +00:00
* @param filePath The path to the file to get the lines from.
* @return A list with all lines of the file.
*/
private List<String> getFileLines(String filePath) {
try {
return Files.readAllLines(Paths.get(filePath), StandardCharsets.ISO_8859_1);
} catch (IOException e) {
e.printStackTrace();
return List.of();
}
}
}