簡體   English   中英

BufferedReader和Stream Line Java 8

[英]BufferedReader and stream Line Java 8

使用BufferedReader:我有一個文本文件,具有與下面列出的相似的行。 文本文件行示例:

ABC  DEF  EFG 1.2.3.3 MGM -Ba\
10.101.0.10

我如何在-Ba之后刪除char \\行的結尾,並將下一行/字段連接到第一行以產生新行,然后將其存儲在數組中以供以后打印。

我想要的是,如果在第一行的末尾找到\\則能夠加入兩行,然后將由定界符“”分隔的“ 2行”的每個元素(現在一個行)分配給我在其中的字段可以稍后再打來打印。 但我也想刪除該行末尾的多余字符\\

這是我想要作為新組合線存儲在數組中的東西

Field-1 Field-2 Field-3 Field-4 Field-5 Field-6;

新數組的第一行等於

Field-1 = ABC Field-2 = DEF Field-3 = EFG Field-4 = 1.2.3.3 Field-5 = -Ba Field-6 = 10.101.0.10; 

如果在第一行的末尾找到\\ char,將生成新的組合行(合二為一)。

到目前為止,我在Bufferedreader類中擁有什么

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;
    }
}

您正在讀取文件兩次。 一個確定其長度,另一個確定其長度。 請改用可變大小的容器,這樣您就可以在不知道文件長度的情況下讀取文件。

您可以使用string.chartAt(string.length-1)檢測行是否以'\\'結尾。

這是將這兩個原則付諸實踐的代碼:

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:

public List<String> OpenFile() throws IOException {
.......
    return lines; /// Instead of: return lines.toArray( new String[lines.size()] );
}

它會像這樣使用:

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() );
    }
}

這將讀取一個文本文件,並將以'\\'結尾的所有行連接到下一行。

這里有兩個重要的注意事項,它假定輸入正確並且\\字符是該行中的最后一個字符(如果不正確,則必須清除輸入),並且文件的最后一行不結束用反斜杠。

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.
}

您可以使用裝飾器模式定義具有所需行為的新BufferedReader 在這里,我對BufferedReader進行了子類化,以覆蓋.readLine()的行為,以便將以給定字符結尾的行視為連續。

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一樣使用它,例如:

try (BufferedReader reader = new ConcatBufferedReader('\\',
         Files.newBufferedReader(yourFile))) {
  ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM