VL-Programmieren/VL12/Aufgabe01/StringFeld.java

71 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.
* @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()];
for(int i = 0; i < lines.size(); i++) {
this.values[i] = lines.get(i).split(separator)[index];
}
}
/**
* Method to get a value.
* @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.
* @param index The index of the value.
* @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;
if(this.values[index].length() > maxLength) {
return this.values[index].substring(0, maxLength);
} else {
return this.values[index];
}
}
/**
* Method to get all the lines of a file.
* @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();
}
}
}