【问题标题】:Read specific characters from file从文件中读取特定字符
【发布时间】:2014-12-04 10:02:03
【问题描述】:

我正在尝试从文本文件中读取特定字符以进行存储以供进一步处理。我试图读取的文件布局为:

45721 Chris Jones D D C P H H C D
87946 Jack Aaron H H H D D H H H
43285 Ben Adams C F C D C C C P
24679 Chuck Doherty F F F P C C C F
57652 Dean Betts F C F C D P D H
67842 Britney Dowling D D F D D F D D
22548 Kennedy Blake P F P F P F P P

我要阅读的特定字符是个人姓名后面的 8 个字符。我曾尝试寻找解决方案,但我对 Java 非常陌生,并且在理解逻辑时遇到问题,因此将不胜感激。

【问题讨论】:

  • 你要取名吗?
  • 如果数据非常一致,可以使用.split(" ")将字符串用空格分割。
  • 查看扫描仪类
  • @getlost 不,我想去掉名字后面的 8 个字符

标签: java file char


【解决方案1】:

试试 Scanner 类,它非常适合这些东西

Scanner in = new Scanner(new File("./myfile.txt"));
while(in.hasNextLine()){
    //read in a whole line
    String line = in.nextLine();

    //sanity check so we don't try to substring an empty string from an empty line at the end of the file.
    if(line.length() == 0){
        continue;
    }

    //15 chars from the end it 8 chars + 7 spaces
    //We go back 16 though since the string index starts at 0, not 1.
    line = line.subString(line.length()-16, line.length()-1);

    //Now split the string based on any white spaces in between the chars spaces
    String[] letters = line.split(" ");
    //Now do something with your letters array 
}

请注意,这假设您发布的格式非常严格。如果您想进行一些不同的设置,扫描仪还可以逐个读取令牌。 Check out the Scanner documentation.

【讨论】:

  • 当我尝试测试这段代码时,我收到错误“方法 size() 未定义 String 类型”,有什么想法吗?
  • 我的错,我忘记了字符串的大小或长度。更新了我的答案
  • 那么我现在如何只打印数组以查看它是否正常工作。它只是 System.out.printIn(letters); ?
  • 该语法将简单地打印数组的哈希码。您可以使用 for 循环并单独打印出元素,也可以使用 System.out.println(Arrays.tostring(letters));
【解决方案2】:

如果该行的格式始终为 #### FirstName LastName A1 A2 A3 A4 A5 A6 A7 A8 ,那么下面的代码应该可以工作:

String line = "57363 Joy Ryder D D C P H H C D";
String[] cols = line.split("\\s+"); // split line by one or more whitespace chars

cols[0] 将包含数字,cols[3]cols[10] 将包含您想要的字母,A1 到 A8。

如果有中间名或没有姓氏,索引会有所不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多