java 如何在Java中读取和拆分txt文件的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13775334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read and split the contents of txt file in Java?
提问by AyaZoghby
I want to read the whole text of a file and then split it according to specific delimiters. How could I do so in Java?
我想阅读文件的整个文本,然后根据特定的分隔符将其拆分。我怎么能在Java中这样做?
回答by Rahul
try{
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// split the line on your splitter(s)
String[] splitted = strLine.split("-"); // here - is used as the delimiter
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
回答by droidchef
Read the contents. Choose a delimiter up to which you want to check each line/word or phrase for the splitting. Have a switch case setup. Whatever content you find based on the switch case you can perform actions. Say you can write in different text files from different cases.
阅读内容。选择一个分隔符,您要检查每个行/单词或短语以进行拆分。有一个开关盒设置。无论您根据 switch case 找到什么内容,您都可以执行操作。假设您可以在不同情况下写入不同的文本文件。