所以我有這個任務要做,我需要將訊息中的文本縮寫擴展為 .csv 檔案中的完整形式,我將該檔案加載到 HashMap 中,鍵作為縮寫,值作為完整形式。有一個回圈來遍歷鍵和 if 陳述句,如果找到任何縮寫,它會將縮寫替換為完整形式。我有點想通了,它正在正常作業,但我想將這個更改后的字串(擴展了縮寫)發送到 if 陳述句之外的其他地方,以將完整訊息保存到檔案中。我知道這個字串只存在于這個 if 陳述句中,但也許還有另一種方法呢?或者也許我做錯了什么?我對 Java 有點生疏了,所以也許有一個我不知道的簡單解釋。這是我的代碼:
public class AbbreviationExpander {
static void AbrExpander(String messageBody) {
//read the .csv file
String csvFile = "textwords.csv";
String line = "";
String cvsSplitBy = ",";
String bodyOut = messageBody;
HashMap<String, String> list = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] abbreviatonFile = line.split(cvsSplitBy);
//load the read data into the hashmap
list.put(abbreviatonFile[0], abbreviatonFile[1]);
}
for (String key : list.keySet()) {
//if any abbreviations found then replace them with expanded version
if (messageBody.contains(key)) {
bodyOut = bodyOut.replace(key, key "<" list.get(key).toLowerCase() ">");
try {
File file = new File("SMS message" System.currentTimeMillis() ".txt");
FileWriter myWriter = new FileWriter(file);
myWriter.write(bodyOut);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
} catch (IOException f) {
f.printStackTrace();
}
}
}
uj5u.com熱心網友回復:
不確定我是否理解你的問題。但我認為您應該將代碼中的不同步驟分開。
我的意思是你try-catch寫輸出的塊應該在 read 之外for-loop和之外try-catch。你for-loop應該在你的閱讀之外try-catch。
public class AbbreviationExpander {
static void AbrExpander(String messageBody) {
String csvFile = "textwords.csv";
String line = "";
String cvsSplitBy = ",";
String bodyOut = messageBody;
HashMap<String, String> list = new HashMap<>();
//read the .csv file
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] abbreviatonFile = line.split(cvsSplitBy);
//load the read data into the hashmap
list.put(abbreviatonFile[0], abbreviatonFile[1]);
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
//if any abbreviations found then replace them with expanded version
for (String key : list.keySet()) {
if (messageBody.contains(key)) {
bodyOut = bodyOut.replace(key, key "<" list.get(key).toLowerCase() ">");
}
}
//output the result in your file
try {
File file = new File("SMS message" System.currentTimeMillis() ".txt");
FileWriter myWriter = new FileWriter(file);
myWriter.write(bodyOut);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/359264.html
