Java-从文本文件创建字符串数组
我有这样一个文本文件:Java-从文本文件创建字符串数组,java,string,Java,String,我有这样一个文本文件: abc def jhi klm nop qrs tuv wxy zzz 我想要一个字符串数组,如: String[] arr = {"abc def jhi","klm nop qrs","tuv wxy zzz"} 我试过: try { FileInputStream fstream_school = new FileInputStream("text1.txt"); DataInputStream data_input =
abc def jhi
klm nop qrs
tuv wxy zzz
我想要一个字符串数组,如:
String[] arr = {"abc def jhi","klm nop qrs","tuv wxy zzz"}
我试过:
try
{
FileInputStream fstream_school = new FileInputStream("text1.txt");
DataInputStream data_input = new DataInputStream(fstream_school);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String str_line;
while ((str_line = buffer.readLine()) != null)
{
str_line = str_line.trim();
if ((str_line.length()!=0))
{
String[] itemsSchool = str_line.split("\t");
}
}
}
catch (Exception e)
{
// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
谁能帮帮我。。。。
所有答案都将不胜感激……使用a读取文件,将每行作为字符串读取,并将它们放在一个数组列表中,在循环结束时调用数组。如果使用Java 7,可以分两行完成,这要感谢:
List line=Files.readAllLines(您的文件,字符集);
String[]arr=lines.toArray(新字符串[lines.size()]);
您可以使用一些输入流或扫描仪逐行读取文件,然后将该行存储在字符串数组中。。示例代码将是
File file = new File("data.txt");
try {
//
// Create a new Scanner object which will read the data
// from the file passed in. To check if there are more
// line to read from it we check by calling the
// scanner.hasNextLine() method. We then read line one
// by one till all line is read.
//
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//store this line to string [] here
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
输出:
[abc, def, jhi, klm, nop, qrs, tuv, wxy, zzz]
根据您的输入,您可以阅读有关扫描仪的更多信息,您就快到了。在循环中,您错过了保持从文件中读取每一行的位置。由于您事先不知道文件中的总行数,请使用集合(动态分配大小)获取所有内容,然后将其转换为
字符串的数组(因为这是您所需的输出)
大概是这样的:
String[] arr= null;
List<String> itemsSchool = new ArrayList<String>();
try
{
FileInputStream fstream_school = new FileInputStream("text1.txt");
DataInputStream data_input = new DataInputStream(fstream_school);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String str_line;
while ((str_line = buffer.readLine()) != null)
{
str_line = str_line.trim();
if ((str_line.length()!=0))
{
itemsSchool.add(str_line);
}
}
arr = (String[])itemsSchool.toArray(new String[itemsSchool.size()]);
}
这不是最佳解决方案。其他更聪明的答案已经给出。这只是您当前方法的一个解决方案 您可以使用readLine函数读取文件中的行并将其添加到数组中
例如:
File file = new File("abc.txt");
FileInputStream fin = new FileInputStream(file);
BufferedReader reader = new BufferedReader(fin);
List<String> list = new ArrayList<String>();
while((String str = reader.readLine())!=null){
list.add(str);
}
//convert the list to String array
String[] strArr = Arrays.toArray(list);
File File=new文件(“abc.txt”);
FileInputStream fin=新的FileInputStream(文件);
BufferedReader读取器=新的BufferedReader(fin);
列表=新的ArrayList();
while((String str=reader.readLine())!=null){
添加(str);
}
//将列表转换为字符串数组
字符串[]strArr=Arrays.toArray(列表);
上面的数组包含您所需的输出。这是我从文本文件创建数组生成随机电子邮件的代码
import java.io.*;
public class Generator {
public static void main(String[]args){
try {
long start = System.currentTimeMillis();
String[] firstNames = new String[4945];
String[] lastNames = new String[88799];
String[] emailProvider ={"google.com","yahoo.com","hotmail.com","onet.pl","outlook.com","aol.mail","proton.mail","icloud.com"};
String firstName;
String lastName;
int counter0 = 0;
int counter1 = 0;
int generate = 1000000;//number of emails to generate
BufferedReader firstReader = new BufferedReader(new FileReader("firstNames.txt"));
BufferedReader lastReader = new BufferedReader(new FileReader("lastNames.txt"));
PrintWriter write = new PrintWriter(new FileWriter("emails.txt", false));
while ((firstName = firstReader.readLine()) != null) {
firstName = firstName.toLowerCase();
firstNames[counter0] = firstName;
counter0++;
}
while((lastName= lastReader.readLine()) !=null){
lastName = lastName.toLowerCase();
lastNames[counter1]=lastName;
counter1++;
}
for(int i=0;i<generate;i++) {
write.println(firstNames[(int)(Math.random()*4945)]
+'.'+lastNames[(int)(Math.random()*88799)]+'@'+emailProvider[(int)(Math.random()*emailProvider.length)]);
}
write.close();
long end = System.currentTimeMillis();
long time = end-start;
System.out.println("it took "+time+"ms to generate "+generate+" unique emails");
}
catch(IOException ex){
System.out.println("Wrong input");
}
}
}
import java.io.*;
公共类生成器{
公共静态void main(字符串[]args){
试一试{
长启动=System.currentTimeMillis();
String[]firstNames=新字符串[4945];
字符串[]lastNames=新字符串[88799];
String[]emailProvider={“google.com”、“yahoo.com”、“hotmail.com”、“onet.pl”、“outlook.com”、“aol.mail”、“proton.mail”、“icloud.com”};
字符串名;
字符串lastName;
int计数器0=0;
int计数器1=0;
int generate=1000000;//要生成的电子邮件数
BufferedReader firstReader=新的BufferedReader(新文件阅读器(“firstNames.txt”);
BufferedReader lastReader=新的BufferedReader(新文件阅读器(“lastNames.txt”);
PrintWriter write=新的PrintWriter(新的FileWriter(“emails.txt”,false));
而((firstName=firstReader.readLine())!=null){
firstName=firstName.toLowerCase();
名字[0]=名字;
计数器0++;
}
而((lastName=lastReader.readLine())!=null){
lastName=lastName.toLowerCase();
lastNames[counter1]=lastName;
计数器1++;
}
for(int i=0;iHello Edward,欢迎使用SO。如果您的问题已得到回答,请选择有效答案,谢谢:)+1我不知道readAllLines实用程序对小文件可能很方便。@assylias:我尝试过这个,但它在字符集上显示红色下划线。我该怎么办?提供文件使用的字符集-通常类似于charset.forName(“UTF-8”)
注意,他希望每一行都是数组中的一个条目,而不是被该行中的令牌分割。谢谢,我认为这是可行的,但在LogCat中,显示:Error:/text1.txt:open failed:enoint(没有这样的文件或目录)您应该在当前目录中有您的text1.txt
输入文件(正如您在问题中所做的那样)否则你需要提供路径和文件名。是的,我把它放在同一个文件夹中。对不起,我忘了提到我正在开发android应用程序。它会和普通Java应用程序的路径相同吗?是的,在同一个文件夹中,但最好不要把配置文件和源代码弄乱。你最好创建一个文件夹,然后放置我但我仍然发现了错误。一些教程提到了android的getFileDir()方法,以便找到文件的路径。当我使用它时,在LogCat中要求我将文件放入/data/data中/
{"abc def jhi","klm nop qrs","tuv wxy zzz"}
File file = new File("abc.txt");
FileInputStream fin = new FileInputStream(file);
BufferedReader reader = new BufferedReader(fin);
List<String> list = new ArrayList<String>();
while((String str = reader.readLine())!=null){
list.add(str);
}
//convert the list to String array
String[] strArr = Arrays.toArray(list);
import java.io.*;
public class Generator {
public static void main(String[]args){
try {
long start = System.currentTimeMillis();
String[] firstNames = new String[4945];
String[] lastNames = new String[88799];
String[] emailProvider ={"google.com","yahoo.com","hotmail.com","onet.pl","outlook.com","aol.mail","proton.mail","icloud.com"};
String firstName;
String lastName;
int counter0 = 0;
int counter1 = 0;
int generate = 1000000;//number of emails to generate
BufferedReader firstReader = new BufferedReader(new FileReader("firstNames.txt"));
BufferedReader lastReader = new BufferedReader(new FileReader("lastNames.txt"));
PrintWriter write = new PrintWriter(new FileWriter("emails.txt", false));
while ((firstName = firstReader.readLine()) != null) {
firstName = firstName.toLowerCase();
firstNames[counter0] = firstName;
counter0++;
}
while((lastName= lastReader.readLine()) !=null){
lastName = lastName.toLowerCase();
lastNames[counter1]=lastName;
counter1++;
}
for(int i=0;i<generate;i++) {
write.println(firstNames[(int)(Math.random()*4945)]
+'.'+lastNames[(int)(Math.random()*88799)]+'@'+emailProvider[(int)(Math.random()*emailProvider.length)]);
}
write.close();
long end = System.currentTimeMillis();
long time = end-start;
System.out.println("it took "+time+"ms to generate "+generate+" unique emails");
}
catch(IOException ex){
System.out.println("Wrong input");
}
}
}