簡體   English   中英

如何從文件中讀取字符串並拆分以獲取數據字符串?

[英]How to read a string from file and split to get a data string?

我需要從文件中獲取一個字符串。 我知道如何使用 BufferedReader 讀取整個文件,我知道如何獲得“Integer: 5”之類的值我可以從中獲得 Integer 5 但我不知道如何做同樣的事情並從中獲得整個 String它。 我的意思是,假設我在文件中寫入了“數據:這是一個數據字符串”。 我需要知道如何讀取字符串並從中獲取“這是一個數據字符串”。

EDIT: This is the text in the file that I need to read 
https://pastebin.com/gc9vFLGD

and this is the code that I have tried.

https://pastebin.com/uDfasn7i

您的數據並不簡單,僅使用 split 並且您的代碼也不正確。

1.首先,用“,”分割你的數據模式看起來像dataName:dataValue

2.接下來,如果你用 ":" 分割你的數據,你將面臨 dataValue 也可能包含 ":" 並且分割不會按預期工作的問題。 (我建議用第一個字符 ':' 分割)

3.在你的dataValue里面還包含模式AA:BB->繼續定義規則但在某些情況下拆分不能解決你的規則的數據。 我向您展示了使用 Pattern 和 String 獲取數據的簡單示例(在第 2 步中)。

    public static void main (String ...args){
    String input = "Data: Parent data: Child data";
    String regex = "[:]"; // regular expression
    // Using Pattern class
    Pattern pattern = Pattern.compile(regex);
    String output1 = pattern.split(input,2)[1];
    // Using String class
    String output2 = input.split(regex,2)[1];
    System.out.println(output1);
    System.out.println(output2);
  }

如果您需要第 3 步中的更多數據,請了解正則表達式(正則表達式)並查看 Pattern 的 java 文檔以了解其工作原理。 之后定義您自己的規則來解析原始數據。 也許很難,但正則表達式非常強大,可以完成許多任務。 如果有任何問題,至少再次展示您的研究和問題。

這是您問題的答案...

我希望,該文件實際上不會看起來像那樣,因為等待發生的事情很混亂......使它成為單獨的行,而不是使用我的代碼......它使它變得更加簡單......

現在有兩件事你應該知道:

1.)您可以使用以下命令獲取字符串的第二部分:

String text;
String[] scan=text.split(": ");
String ret=scan[1];

它的作用是將包含:的字符串分開,然后抓取字符串的第二部分...

2.)如果您已經知道將在該字符串中的文本,您可以使用以下命令:

public static String replaceAllString(String s, String a, String b) {
    s.replace(a, b);
    return s;
}

public static void Example() {
    String text;
    text = replaceAllString(line, knownValue, "");

    //knownValue: is the part of the String you DO NOT want in it...
    //line: is the line from the file
}

現在它所做的是它而不是拆分字符串,它只是獲取字符串原始值,並刪除您不想要的字符串中的已知值(這不會編輯文件中的行)...

現在,如果您必須將它與文件一起保存為一大堆亂七八糟的東西,那么我建議您這樣做:

public static String[] getInfo() {
    //assuming you have already done the file buffer read...
    String[] sep=line.split(", ");
    return sep;
}

public static String grab(String start) {
    String sep=grabInfo();
    String info="";
    for (String s : sep) {
        if (s.contains(start)) {
            String[] c=s.split(start);
            info=c[1];
            break;
        }
    }
    return info;
}

我認為@msagala25 的評論是正確的,最簡單的事情之一是使用正則表達式(RegEx) 從字符串中檢索 1 個(或可能更多)特定子字符串與 Java 的java.util結合使用.regex 模式和匹配器類。

下面是一個方法 ( getBetween() ) 來演示如何從字符串中檢索幾乎任何您想要的子字符串,前提是您提供左字符串和右字符串標簽(可以這么說)。 讓我們看一下文本文件中的第二行:

String fileLine = "[Slot Number: 0, Item ID: 399, Item Data: ItemStack{NETHER_STAR x 1, "
                + "UNSPECIFIC_META:{meta-type=UNSPECIFIC, display-name=§6Kit Selector, "
                + "lore=[§eUse this to, §eselect a kit!]}}]";

如果我們希望Item ID:元素的字符串值為399 ,則我們的左字符串標簽將是: "Item ID:"而我們的右字符串標簽將是: "," ,例如:

String leftTag = "Item ID:";
String rightTag = ",";
String[] data = getBetween(a, leftTag, rightTag);
System.out.println("The Item ID in String is: " + data[0]);

控制台窗口將顯示: The Item ID in String is: 399

getBetween()方法返回一維字符串數組的唯一原因是所提供的fileLine字符串可能包含一組以上的左右字符串標簽。 該方法可以很容易地增強為只返回一個特定實例或提供的左和右字符串標簽之間的特定實例。 目前,如果您知道有多個實例,則需要遍歷數組以獲取所需的實例。 在上面提供的fileLine串,我們知道僅存在一個的左字符串標記實例“項ID:”,其中包含的右字符串標記“”所提供的fileLine串內因此上述示例代碼僅使用該陣列的索引0以顯示所需的內容。

默認情況下,此方法會在將結果放入返回的一維字符串數組之前從結果中修剪任何前導或尾隨制表符和/或空格。 這可以通過提供布爾值 false 來通過trimFound可選參數選擇性地關閉。 忽略字母大小寫(默認為 false)也可以更改,也可以應用為ignoreLetterCase可選參數提供布爾值 true(閱讀提供的注釋部分)。

這是getBetween()方法:

/**
 * Retrieves any string data located between the supplied string leftString
 * parameter and the supplied string rightString parameter.<br><br>
 *
 * This method will return all instances of a substring located between the
 * supplied Left String and the supplied Right String which may be found
 * within the supplied Input String.<br>
 *
 * @param inputString (String) The string to look for substring(s) in.
 *
 * @param leftString (String) What may be to the Left side of the substring we want 
 * within the main input string.
 *
 * @param rightString (String) What may be to the Right side of the substring we want 
 * within the main input string..
 *
 * @param options (Optional - Boolean - 2 Parameters):<pre>
 *
 *      ignoreLetterCase    - Default is false. This option works against the
 *                            string supplied within the letString parameter
 *                            and the string supplied within the rightString
 *                            parameter. If set to true then letter case is
 *                            ignored when searching for strings supplied in
 *                            these two parameters. If left at default false
 *                            then letter case is not ignored.
 *
 *      trimFound           - Default is true. By default this method will trim
 *                            off leading and trailing white-spaces from found
 *                            sub-string items. General sentences which obviously
 *                            contain spaces will almost always give you a white-
 *                            space within an extracted sub-string. By setting
 *                            this parameter to false, leading and trailing white-
 *                            spaces are not trimmed off before they are placed
 *                            into the returned Array.</pre>
 *
 * @return (1D String Array) Returns a Single Dimensional String Array
 * containing all the sub-strings found within the supplied Input String
 * which are between the supplied Left String and supplied Right String.
 * You can shorten this method up a little by returning a List&lt;String&gt;  
 * ArrayList and removing the 'List to 1D Array' conversion code at the end 
 * of this method. This method initially stores its findings within a List 
 * object anyways.
 */
public static String[] getBetween(String inputString, String leftString, String rightString, boolean... options) {
    // Return nothing if nothing was supplied.
    if (inputString.equals("")) {
        return null;
    }

    // Prepare optional parameters if any supplied.
    // If none supplied then use Defaults...
    boolean ignoreCase = false; // Default.
    boolean trimFound = true;   // Default.
    if (options.length > 0) {
        if (options.length >= 1) {
            ignoreCase = options[0];
        }
        if (options.length >= 2) {
            trimFound = options[1];
        }
    }

    // Remove any ASCII control characters from the
    // supplied string (if they exist).
    String modString = inputString.replaceAll("\\p{Cntrl}", "");

    // Establish a List String Array Object to hold
    // our found substrings between the supplied Left
    // String and supplied Right String.
    List<String> list = new ArrayList<>();

    /// Use Pattern Matching to locate our possible
    // substrings within the supplied Input String.
    String regEx = Pattern.quote(leftString) + "(.*?)" + Pattern.quote(rightString);
    if (ignoreCase) { regEx = "(?i)" + regEx; }
    Pattern pattern = Pattern.compile(regEx);
    Matcher matcher = pattern.matcher(modString);
    while (matcher.find()) {
        // Add the found substrings into the List.
        String found = matcher.group(1);
        if (trimFound) {
            found = found.trim();
        }
        list.add(found);
    }

    String[] res;
    // Convert the ArrayList to a 1D String Array.
    // If the List contains something then convert
    if (list.size() > 0) {
        res = new String[list.size()];
        res = list.toArray(res);
    } // Otherwise return Null.
    else {
        res = null;
    }
    // Return the String Array.
    return res;
}

如前所述,Pattern/Matcher 用於使用正則表達式檢索所需的子字符串。 根據是否要忽略字母大小寫,使用了兩種不同的表達式。 以下是每個表達式的解釋:

如果不忽略字母大小寫: "\\\\Q" + leftStringTag + "\\\\E(.*?)\\\\Q" + rightStringTag + "\\\\E"

在此處輸入圖片說明

如果忽略字母大小寫: "(?i)\\\\Q" + leftStringTag + "\\\\E(.*?)\\\\Q" + rightStringTag + "\\\\E"

在此處輸入圖片說明

請查看 apache IOUtils 的 java.nio 包,它提供了逐行讀取文件的直接方法。 閱讀完一行后,您需要使用基於正則表達式的搜索來從該字符串中獲取所需內容。

另外我看到你只是在閱讀直到找到特定的字符串,這是要求嗎?

此外,您沒有關閉文件,因此這里也存在資源泄漏。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM