如何在java中使用scanner类
我想将我的names.rtf文件(包含人名字符串names.rtf=ABHISHEK,ANKIT,…..ASHISH)转换为单个字符串[]name,这样name={ABHISHEK,ANKIT,….ASHISH} 下面是我的代码建议如何在java中使用scanner类,java,Java,我想将我的names.rtf文件(包含人名字符串names.rtf=ABHISHEK,ANKIT,…..ASHISH)转换为单个字符串[]name,这样name={ABHISHEK,ANKIT,….ASHISH} 下面是我的代码建议 import java.io.*; import java.util.Scanner; public class FileScan { public static void main(String[] args) throws IOException {
import java.io.*;
import java.util.Scanner;
public class FileScan {
public static void main(String[] args) throws IOException {
Scanner s = null;
String thestring ="";
try {
s = new Scanner(new BufferedReader(new FileReader("/Users/abhishekkumar/Desktop/names1.rtf")));
while (s.hasNextLine()) {
thestring+=(s.nextLine());
thestring+="\n";
}
} finally {
if (s != null) {
s.close();
}
}
System.out.println(thestring);
}
}
首先,为什么要使用scanner类以这种方式读取文件,包括bufferedReader、fileReader等?使用:-
File file = new File("filename.fileformat");
Scanner scanner = new Scanner(file);
在评论中查看您的文件的一个可能的解决方案是:-
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// Location of file to read
File file = new File("data.rtf");
String line="";
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
//System.out.println(line);
}
String[] nameArray=line.split(",");
for(String s:nameArray){
System.out.print(s+" "); //parse the array to verify entries
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
首先,你没有在数组中插入名字,其次,你面临什么问题?@Batty是的,我正在插入字符串。我从网络上获取了这段代码。我想从你那里得到的是,将个人名字字符串转换成字符串[]。My names.rtf包含500个用逗号分隔的人的名字。请显示文件的一些真实内容。是否包括括号和引号?为什么要数组而不是列表?文件中的一行是所有500个名称,并且您确定每个名称都包含在其中。发布真实的文件内容?@feuerball my names.txt是我要将其转换为名称的字符串[]。