import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Filereader {
public static void main(String[] args) throws IOException {
File fil = new File("trans1.txt");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
//Create scanner to read contents of a file
Scanner scanner = new Scanner(new File("trans1.txt"));
//Create an array to store contents of a file after reading them
String [] tall = new String [100];
int i = 0;
while(scanner.hasNext()){
//Create StringTokenizer object
StringTokenizer st = new StringTokenizer(scanner.next(),"< , { } >", true);
tall[i] = scanner.next();
System.out.println(tall[i]);
i++;
}
in.close();
}
}
我想使用上面的代码将文件内容读入数组,并将存储在数组中的值打印到屏幕。每次我运行代码我没有得到所需的输出,有人可以帮助。我的文件内容如下;
5
<0,{p1}>
<0,{p1}> -1-> <1>
<1,{p1}> -2-> <2><3>
<2,{p0}> -1-> <0>
<3,{p1}> -1-> <4>
<4,{p0}> -1-> <3>
答案 0 :(得分:1)
我是这样做的:
package cruft;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class FileTokenizer
{
private static final String DEFAULT_DELIMITERS = "< , { } >";
private static final String DEFAULT_TEST_FILE = "data/trans1.txt";
public static void main(String[] args)
{
try
{
String fileName = ((args.length > 0) ? args[0] : DEFAULT_TEST_FILE);
FileReader fileReader = new FileReader(new File(fileName));
FileTokenizer fileTokenizer = new FileTokenizer();
List<String> tokens = fileTokenizer.tokenize(fileReader);
System.out.println(tokens);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public List<String> tokenize(Reader reader) throws IOException
{
List<String> tokens = new ArrayList<String>();
BufferedReader br = null;
try
{
br = new BufferedReader(reader);
Scanner scanner = new Scanner(br);
while (scanner.hasNext())
{
StringTokenizer st = new StringTokenizer(scanner.next(), DEFAULT_DELIMITERS, true);
while (st.hasMoreElements())
{
tokens.add(st.nextToken());
}
}
}
finally
{
close(br);
}
return tokens;
}
public static void close(Reader r)
{
try
{
if (r != null)
{
r.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
如果我针对你的文件运行它,那么这就是我得到的输出:
C:\JDKs\jdk1.6.0_13\bin\java cruft.FileTokenizer
[5, <, 0, ,, {, p1, }, >, <, 0, ,, {, p1, }, >, -1-, >, <, 1, >, <, 1, ,, {, p1, }, >, -2-, >, <, 2, >, <, 3, >, <, 2, ,, {, p0, }, >, -1-, >, <, 0, >, <, 3, ,, {, p1, }, >, -1-, >, <, 4, >, <, 4, ,, {, p0, }, >, -1-, >, <, 3, >]
你没有说出你期望的输出。
答案 1 :(得分:0)
首先你应该说明你的“期望输出”是什么。 其次,在你提供的代码中,你甚至不使用你的标记器,你只是无缘无故地创建它。 第三,你在循环中调用scanner.next()两次,可能是无意中跳过了一半的令牌。 第四,为什么同时使用Scanner和StringTokenizer?我以为他们做的几乎是一样的。