2012-04-08 57 views
1

现在我想存储是这样一个文本文件:从文本文件读取时如何忽略数字?

1个苹果

2香蕉

3橙色

4猞猁

5卡布奇诺

等等转换成数据结构。这样做的最好方法是以某种方式将int映射到字符串,还是应该创建一个数组列表?我应该在我自己存储这些单词的时候,不考虑int和任何空格,并且只保留单词本身。在阅读时如何忽略整数?这是我现在砍死在一起代码:

public Dictionary(String filename) throws IOException { 
    if (filename==null) 
     throw new IllegalArgumentException("Null filename"); 
    else{ 
     try { 
      BufferedReader in = new BufferedReader(new FileReader(filename)); 
      String str; 
      int numLines=0; 
      while ((str = in.readLine()) != null) { 
       numLines++; 
      } 
      String[] words=new String[numLines]; 
      for (int i=0; i<words.length;i++){ 
       words[i]=in.readLine(); 
      } 

      in.close(); 
     } catch (IOException e) { 
    } 
    } 

}

预先感谢您的帮助!

+0

如果我没有记错的话,你已经计算的线路时,读取该文件的数据。所以在第二个周期中没有数据需要读取。使用Java集合来存储动态增长的一组行。在将它们存储到Java对象层次结构中之前,您不需要对它们进行计数。 – 2012-04-08 18:35:27

回答

2

只实现正则表达式的威力:

List texts<String> = new ArrayList<String>(); 
Pattern pattern = Pattern.compile("[^0-9\\s]+"); 
String text = "1 apple 2 oranges 3 carrots"; 
Matcher matcher = pattern.matcher(text); 

while (matcher.find()) { 
    texts.add(matcher.group(0)); 
} 

正则表达式都非常受追捧。编译方法用于编译你的搜索模式,你在参数中看到的数字是为了防止他们进入你的搜索。所以它是完全安全的。使用Apache的IOUtilities将文本文件转换为字符串

+0

我真的不确定什么正则表达式是... Pattern.compile(“[^ 0-9 \\ s] +”)是什么意思?它也是作为文本文件而不是字符串输入的......所以为了这个工作,我必须将文本文件转换为字符串吗?感谢您的帮助。 – flymonkey 2012-04-08 18:24:50

+0

正则表达式现在非常流行。编译方法用于编译你的搜索模式,你在参数中看到的数字是为了防止他们进入你的搜索。所以它是完全安全的。使用apache的IOUtilities将文本文件转换为字符串 – GingerHead 2012-04-08 18:33:29

0

如果你的话不包含空格,你可以使用String.split(" ")String分成由空格分隔的Strings阵列。

然后只取数组的第二个元素(第一个将是数字)。

此外,String.trim()方法将删除String之前或之后的任何空格。

注意:您可能需要执行一些错误检查(如果String未按预期格式化,该怎么办)。但是这个代码片断给出了基本思路:

... 
String s = in.readLine(); 
String[] tokens = s.split(" "); 
words[i] = tokens[1].trim(); 
... 
0

如果你想要做的事很容易只是串通过计算数字的原创作品:

int t = 0; 
while (word.charAt(t) >= '0' && word.charAt(t) <= '9') 
    ++t; 

word = word.substring(t); 

如果话绝不会包含空格,你也可以使用word.split(" ")[1]

2

这不能工作,因为你已经在文件的末尾,所以in.readLine()方法将返回null。

我会用地图来存储的名称和数量......是这样的:

HashMap<String, Integer> map = new HashMap<String, Integer>(); 

while((line = br.readLine() !=null){ 
    //also check if the array is null and the right size, trim, etc. 
    String[] tmp = line.split(" "); 
    map.put(tmp[1], Integer.parseInt(tmp[0])); 
} 

否则,您可以使用扫描仪类的尝试。祝你好运。

2

您可以试一试regular expressions

Pattern p = Pattern.compile("[^0-9\\s]+"); 
String s = "1 apple 2 oranges"; 

Matcher m = p.matcher(s); 

while (m.find()) { 
    System.out.println(m.group(0)); 
} 

输出=

苹果

橘子

为了得到一个正则表达式Java regex tutorial想法。

2

我建议您使用List项目来存储从文件解析的结果。解析每条文本行的一种方法是使用String.split(String)方法。另外请注意,您应该正确处理代码中的例外情况,并且在完成后不要忘记关闭Reader(无论是完美无缺还是例外=>使用finally块)。下面的例子应该让你跟踪...希望这有助于。

 

package test; 

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.io.Reader; 
import java.util.ArrayList; 
import java.util.List; 


public class Main { 

    public static void main(String[] args) throws IOException { 
    Main m = new Main(); 
    m.start("test.txt"); 
    } 

    private void start(String filename) throws IOException { 
    System.out.println(readFromFile(filename)); 
    } 

    private final class Item { 
    private String name; 
    private int id; 
    public Item(String name, int id) { 
     this.name = name; 
     this.id = id; 
    } 
    public int getId() { 
     return id; 
    } 
    public String getName() { 
     return name; 
    } 
    @Override 
    public String toString() { 
     return "Item [name=" + name + ", id=" + id + "]"; 
    } 
    } 

    private List<Item> readFromFile(String filename) throws IOException { 
    List<Item> items = new ArrayList<Item>(); 
    Reader r = null; 
    try { 
     r = new FileReader(filename); 
     BufferedReader br = new BufferedReader(r); 
     String line = null; 
     while ((line = br.readLine()) != null) { 
     String[] lineItems = line.split(" "); 
     if (lineItems.length != 2) { 
      throw new IOException("Incorrect input file data format! Two space separated items expected on every line!"); 
     } 
     try { 
      int id = Integer.parseInt(lineItems[0]); 
      Item i = new Item(lineItems[1], id); 
      items.add(i); 
     } catch (NumberFormatException ex) { 
      throw new IOException("Incorrect input file data format!", ex); // JDK6+ 
     } 
     } 
    } finally { 
     if (r != null) { 
     r.close(); 
     } 
    } 
    return items; 
    } 

} 
 
0

nstead使用缓冲读取器使用Scanner类和,而不是使用一个阵列使用ArrayList,像这样的:

import java.util.Scanner; 
import java.util.ArrayList; 

public class Dictionary { 
    private ArrayList strings = new ArrayList(); 

code... 

public Dictionary(String fileName) throws IOException { 

code... 

try { 
    Scanner inFile = new Scanner(new fileRead(fileName)); 

    ArrayList.add("Dummy"); // Dummy value to make the index start at 1 
    while(inFile.hasNext()) { 
    int n = inFile.nextInt(); // this line just reads in the int from the file and 
           // doesn't do anything with it 
    String s = inFile.nextLine().trim(); 

    strings.add(s); 
    } 
    inFile.close(); // don't forget to close the file 
} 

,然后因为你的数据变为1,2, 3,4,5,您可以使用索引来检索每个项目的编号。

通过这样做:

for(int i = 1; i < strings.size(); i++) { 
int n = i; 
String s = n + " " + strings.get(i); 
System.out.println(s); 
} 
相关问题