[英]Returning Strings from a file between 2 specified strings in java
我一直在搜索 web,但似乎找不到可行的解決方案。 我有一個包含這些行的文件:
Room 1
Coffee
Iron
Microwave
Room_end
Room 2
Coffee
Iron
Room_end
我想打印 Room 1 和 Room_end 之間的所有字符串。 我希望我的代碼在找到 Room 1 時開始,在 Room 1 之后打印行,並在到達它找到的第一個 Room_end 時停止。
private static String LoadRoom(String fileName) {
List<String> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
result = reader.lines()
.dropWhile(line -> !line.equals("Room 1"))
.skip(1)
.takeWhile(line -> !line.equals("Room_end"))
.collect(Collectors.toList());
} catch (IOException ie) {
System.out.println("Unable to create " + fileName + ": " + ie.getMessage());
ie.printStackTrace();
}
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i).getname());//error on getname because it cant work with Strings
}
}
class Model {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
我能夠獲得一種方法來打印文件的所有字符串,但不能打印特定范圍的字符串。 我還嘗試使用 Stream。 我的代碼感覺很亂,但我已經研究了一段時間,它似乎只會變得更亂。
public static Map<String, List<String>> getRooms(String path) throws IOException {
Map<String, List<String>> result = new HashMap<>();
try (Scanner sc = new Scanner(new File(path))) {
sc.useDelimiter("(?=Room \\d+)|Room_end");
while (sc.hasNext()) {
Scanner lines = new Scanner(sc.next());
String room = lines.nextLine().trim();
List<String> roomFeatures = new ArrayList<>();
while (lines.hasNextLine()) {
roomFeatures.add(lines.nextLine());
}
if (room.length() > 0) {
result.put(room, roomFeatures);
}
}
}
return result;
}
是為您的“房間文件”執行此操作的一種方法,盡管它確實應該通過制作Room
bean 來保存數據而變得更加面向對象。 Output 與您的文件: {Room 2=[Coffee, Iron ], Room 1=[Coffee, Iron, Microwave]}
切換了我的代碼並使用了這個:
private static String loadRoom(String fileName) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null; //we start with empty info
String ls = System.getProperty("line.separator"); //make a new line
while ((line = reader.readLine()) != null) { //consider if the line is empty or not
if (line.equals("Room 1")) { //condition start on the first line being "Room 1"
line = reader.readLine(); // read the next line, "Room 1" not added to stringBuilder
while (!line.equals("Room_end")) { //check if line String is "Room_end"
stringBuilder.append(line);//add line to stringBuilder
stringBuilder.append(ls);//Change Line in stringBuilder
line = reader.readLine();// read next line
}
}
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
這是一個使用掃描儀和標志的解決方案。 您可以選擇在讀取“Room_end”時中斷循環
import java.util.Scanner;
import java.io.*;
public class Main{
private static String loadRoom(String fileName) throws IOException {
Scanner s = new Scanner(new File(fileName));
StringBuilder sb = new StringBuilder();
boolean print = false;
while(s.hasNextLine()){
String line = s.nextLine();
if (line.equals("Room 1")) print = true;
else if (line.equals("Room_end")) print = false;
else if (print) sb.append(line).append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
try {
String content = loadRoom("content.txt");
System.out.println(content);
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}
我認為如果你想在這里使用 lambda 表達式會有問題:
lambda 表達式是函數式編程,而函數式編程需要不變性,這意味着不應該有 state 相關問題,您可以調用 function,但在您的情況下應該是相同的,但結果應該是相同的state 指示您是否應該打印該行。
你能試試這個解決方案嗎? 我將它寫在 python 中,但主要是關於位於 scope 之外的變量should_print
should_print = False
result = reader.lines()
for line in result:
if line == "Room 1":
should_print = True
elif line == "Room end":
should_print = False
if should_print:
print(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.