Java 如何从文件中读取字符串并拆分以获取数据字符串?
我需要从文件中获取字符串。我知道如何使用BufferedReader读取整个文件,我知道如何获取一个像Integer:5这样的值,我可以从中获取整数5,但我不知道如何做同样的事情,从中获取整个字符串。我的意思是,假设我有数据:这是一个写在文件中的数据字符串。我需要知道如何读取字符串并从中获取数据字符串Java 如何从文件中读取字符串并拆分以获取数据字符串?,java,file,split,Java,File,Split,我需要从文件中获取字符串。我知道如何使用BufferedReader读取整个文件,我知道如何获取一个像Integer:5这样的值,我可以从中获取整数5,但我不知道如何做同样的事情,从中获取整个字符串。我的意思是,假设我有数据:这是一个写在文件中的数据字符串。我需要知道如何读取字符串并从中获取数据字符串 EDIT: This is the text in the file that I need to read https://pastebin.com/gc9vFLGD and this is
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
请看ApacheIOutils的java.nio包,它提供了逐行读取文件的直接方法。一旦你读了一行,你需要使用一个基于正则表达式的搜索来从这个字符串中得到你需要的东西 我还看到,你只是在阅读,直到你找到一个特殊的字符串,这是要求吗
此外,您没有关闭该文件,因此这里也存在资源泄漏。您的数据不容易使用,而且您的代码也不正确 1.首先,拆分为,数据的模式如下 dataName:dataValue 2.接下来,如果您将数据拆分为:,您将面临数据值也可能包含以下内容的问题: 而split将无法按预期工作。我建议用第一个字符“:”分开 3.在您的dataValue中还包含模式为AA:BB->继续定义规则的数据,但在某些情况下拆分无法解决您的规则。 我向您展示了在步骤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中获得更多数据,让我们了解regex正则表达式,并查看模式的java文档以了解它是如何工作的。然后定义自己的规则来解析原始数据。也许这很难,但regex非常强大,可以完成许多任务。如果有任何问题,至少展示你的研究和问题。这是你问题的答案 我希望,那个文件不会看起来像那个样,因为那个是一个烂摊子等待发生。。。让它成为单独的行,然后使用我的代码。。。这让事情变得简单多了 现在有两件事你应该知道: 一,。您可以使用以下命令获取字符串的第二部分:
String text;
String[] scan=text.split(": ");
String ret=scan[1];
它所做的是分离包含:的字符串,然后抓取字符串的第二部分
二,。如果您已经知道该字符串中的文本,您可以使用:
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的评论是正确的,最简单的方法之一是使用正则表达式从字符串中检索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]);
控制台窗口将显示:字符串中的项目ID为:399
getBetween方法返回一维字符串数组的唯一原因是,提供的文件行字符串可能包含多组左右字符串标记。该方法可以很容易地得到增强,只返回所提供的左字符串标记和右字符串标记之间的一个或多个特定实例。当前,如果您知道有多个实例,则需要遍历数组以获得所需的实例。在上面提供的文件行字符串中,我们知道只有一个Item ID的左字符串标记实例:它在提供的文件行字符串中包含一个右字符串标记,因此上面的示例代码只是使用数组的索引0来显示所需的内容
默认情况下,此方法会在将结果放入返回的1D字符串数组之前修剪结果中的任何前导或尾随制表符和/或空格。通过提供布尔值false,可以通过trimFound可选参数关闭此选项。忽略字母大小写默认值为false也可以更改,也可以应用为ignoreLetterCase可选参数提供布尔值true读取提供的注释部分
下面是getBetween方法:
如前所述,Pattern/Matcher用于使用正则表达式检索所需的子字符串。根据是否忽略字母大小写,使用了两种不同的表达式。以下是对每个表达式的解释:
如果不忽略字母大小写:\\Q+leftStringTag+
\\E.*\\Q+rightStringTag+\\E
如果忽略字母大小写:?i\\Q+左
特林塔格+
\\E.*\\Q+rightStringTag+\\E
尝试使用正则表达式。不确定你的意思。抱歉我的无知,我对java还很陌生。我投票决定以离题的方式结束这个问题,因为它缺乏准备,没有代码链接而没有在这里展示。冷静点,天哪。好的。非常感谢。我将修复文件关闭,我不喜欢使用API。我还将研究Regex。谢谢
/**
* 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<String>
* 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;
}