首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BufferedReader和流线Java 8

BufferedReader和流线Java 8
EN

Stack Overflow用户
提问于 2015-07-09 13:37:46
回答 3查看 2.8K关注 0票数 1

使用BufferedReader:我有一个具有类似行的文本文件,如下所示。文本文件行示例:

代码语言:javascript
复制
ABC  DEF  EFG 1.2.3.3 MGM -Ba\
10.101.0.10

如何在\之后删除char行的末尾,并将下一行/字段连接到第一行,以便有新行,然后将其存储在数组中,以便稍后打印。

我想要的是,如果在第一行的末尾找到了\,那么就能够连接这2行,然后将分隔符“分隔符”分隔的"2行“(现在是一行)的每个元素分配给字段,在那里我可以稍后调用打印。但我也想删除行尾发现的不需要的字符\

下面是我希望在数组中存储的新的组合行

代码语言:javascript
复制
Field-1 Field-2 Field-3 Field-4 Field-5 Field-6;

其中,新数组的第一行将等于

代码语言:javascript
复制
Field-1 = ABC Field-2 = DEF Field-3 = EFG Field-4 = 1.2.3.3 Field-5 = -Ba Field-6 = 10.101.0.10; 

如果在第一行的末尾找到\字符,则将生成新的合并行(2 in 1)。

到目前为止,我在Bufferedreader类中所拥有的

代码语言:javascript
复制
public class ReadFile {

    private String path;

    ReadFile(String filePath) {
        path = filePath;
    }

    public String[] OpenFile() throws IOException {
        FileReader fr = new FileReader(path);
        BufferedReader textReader = new BufferedReader(fr);

        int numberOfLines = readLines();
        String[] textData = new String[numberOfLines];

        for (int i = 0; i < numberOfLines; i++) {
            textData[i] = textReader.readLine();

        }

        textReader.close();
        return textData;

    }
//Not sure if It's better to have while loop instead of this to reach end of file, let me know what you think?
    int readLines() throws IOException {
        FileReader f2r = new FileReader(path);
        BufferedReader bf = new BufferedReader(f2r);
        String aLine;
        int numberOfLines = 0;
        while ((aLine = bf.readLine()) != null) {
            numberOfLines++;

        }
        bf.close();
        return numberOfLines;
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-07-09 14:05:26

这将读取文本文件,并将以“\”结尾的任何行连接到下面一行。

这里有两个重要的注意事项,这假设输入是正确的,\字符是行中的最后一个字符(如果输入不是真,则必须对输入进行清理),并且文件的最后一行不以反斜杠结尾。

代码语言:javascript
复制
try (Bufferedreader br = new BufferedReader(new FileReader(file))) {
    String line;
    StringBuilder concatenatedLine = new StringBuilder();
    List<String> formattedStrings = new ArrayList<String>();
    while((line = br.readLine()) != null){

        //If this one needs to be concatenated with the next,
        if( line.charAt(line.length() -1) == '\\' ){ 
            //strip the last character from the string
            line = line.substring(0, line.length()-1); 
            //and add it to the StringBuilder
            concatenatedLine.append(line);
        }
        //If it doesn't, this is the end of this concatenated line
        else{
            concatenatedLine.append(line);
            //Add it to the formattedStrings collection.
            formattedStrings.add(concatenatedLine.toString());
            //Clear the StringBuilder
            concatenatedLine.setLength(0);
        }
    }

    //The formattedStrings arrayList contains all of the strings formatted for use.
}
票数 1
EN

Stack Overflow用户

发布于 2015-07-09 14:04:04

你正在读两遍这个文件。一个用来确定它的长度,另一个用来读取线条。使用可变大小的容器,这样您就可以在不知道文件长度的情况下读取该文件。

您可以检测一行是否以“string.chartAt”结尾(字符串长度-1)。

下面是将这两项原则付诸实施的代码:

代码语言:javascript
复制
public String[] OpenFile() throws IOException {
    List<String> lines = new ArrayList<>(); // Store read lines in a variable
                                            // size container

    FileReader fr = new FileReader(path);
    BufferedReader textReader = new BufferedReader(fr);

    String partialLine = null; // Holds a previous line ending in \ or
    // null if no such previous line
    for (;;)
    {
        String line = textReader.readLine(); // read next line
        if ( line==null )
        {   // If end of file add partial line if any and break out of loop
            if ( partialLine!=null )
                lines.add(partialLine);
            break;
        }
        boolean lineEndsInSlash =   line.length()!=0 &&
                                    line.charAt(line.length()-1)=='\\';
        String filteredLine; // Line without ending \
        if ( lineEndsInSlash )
            filteredLine = line.substring(0, line.length()-1);
        else
            filteredLine = line;
        // Add this line to previous partial line if any, removing ending \ if any
        if ( partialLine==null )
            partialLine = filteredLine;
        else
            partialLine += filteredLine;
        // If the line does not end in \ it is a completed line. Add to
        // lines and reset partialLine to null. Otherwise do nothing, next
        // iteration will keep adding to partial line
        if ( !lineEndsInSlash )
        {
            lines.add(partialLine);
            partialLine = null;
        }
    }

    textReader.close();

    return lines.toArray( new String[lines.size()] );
}

我将String[]保留为返回类型,因为这可能是您无法避免的要求。但如果可能的话,我建议你把它改为清单。这是一种更适合的类型。

要做到这一点,应该将OpenFile更改如下:

代码语言:javascript
复制
public List<String> OpenFile() throws IOException {
.......
    return lines; /// Instead of: return lines.toArray( new String[lines.size()] );
}

它会像这样使用:

代码语言:javascript
复制
public static void main( String[] args )
{
    try { 
        ReadFile file = new ReadFile("/home/user/file.txt"); 
        List<String> aryLines = file.OpenFile(); 
        for ( String s : aryLines) { 
            System.out.println(s); 
        }
    }
    catch ( IOException ex)
    {
        System.out.println( "Reading failed : " + ex.getMessage() );
    }
}
票数 1
EN

Stack Overflow用户

发布于 2015-07-09 14:09:07

您可以使用装饰图案定义一个新的BufferedReader,它具有您想要的行为。在这里,我对BufferedReader进行了子类化,以覆盖.readLine()的行为,以便它将以给定字符结尾的行视为连续。

代码语言:javascript
复制
public class ConcatBufferedReader extends BufferedReader {
  private final char continues;

  public ConcatBufferedReader(char continues, Reader in) {
    super(in);
    this.continues = continues;
  }

  @Override
  public String readLine() throws IOException {
    StringBuilder lines = new StringBuilder();
    String line = super.readLine();
    while (line != null) {
      if (line.charAt(line.length()-1) == continues) {
        lines.append(line.substring(0, line.length()-1)).append(' ');
      } else {
        return lines.append(line).toString();
      }
      line = super.readLine();
    }
    // Handle end-of-file
    return lines.length() == 0 ? null : lines.toString();
  }
}

然后,您可以像使用任何其他BufferedReader一样使用它,例如:

代码语言:javascript
复制
try (BufferedReader reader = new ConcatBufferedReader('\\',
         Files.newBufferedReader(yourFile))) {
  ...
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31319203

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档