如何在java中读取文本文件中指定的字符

时间:2016-01-20 07:10:08

标签: java file-io

鉴于我有一个文本文件,我知道我可以使用FileReader来阅读chars

in = new FileReader("myFile.txt");
int c;
while ((c = in.read()) != -1)
{ ... }

然而,在我in.read()之后,是否可以用一个字符回溯?有什么方法可以改变in.read()指向的地方吗?也许我可以使用迭代器?

4 个答案:

答案 0 :(得分:0)

如果您只需要回溯一个字符,请考虑将前一个字符保留在变量中,然后在需要时引用该字符。

如果您需要回溯未指定的数量,大多数文件可能更容易将文件内容保存在内存中并处理内容。

正确的答案取决于背景。

答案 1 :(得分:0)

答案 2 :(得分:0)

假设您正在谈论输入流。 您可以使用int java.io.InputStream.read(byte [] b,int off,int len)方法代替第二个参数" off" (for offset)可以用作你想要读取的inputStream的起始点。

另一种方法是首先使用 in.reset()将阅读器重新定位到流的开头,然后 in.skip(long n)移动到所需的位置

答案 3 :(得分:0)

根据您想要实现的目标,您可以查看PushbackInputStreamRandomAccessFile

在下面找到两个片段来演示不同的行为。对于文件public class MyIntegerValidationAttribute : ValidationAttribute { public string[] PropertyNames { get; } public MyIntegerValidationAttribute(params string[] propertyNames) { PropertyNames = propertyNames; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty); //here you have values of your properties var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<int>(); if (YOUR_CUSTOM_CONDITION) { return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName)); } return null; } } public class ViewModel { [MyIntegerValidationAttribute("B", "C", ErrorMessage = "My error message")] public int A { get; set; } public int B { get; set; } public int C { get; set; } } 包含行abc.txt

PushbackInputStream允许您更改流中的数据以便稍后读取。

foobar12345

outout

try (PushbackInputStream is = new PushbackInputStream(
        new FileInputStream("abc.txt"))) {
    // for demonstration we read only six values from the file
    for (int i = 0; i < 6; i++) {
        // read the next byte value from the stream
        int c = is.read();
        // this is only for visualising the behavior
        System.out.print((char) c);
        // if the current read value equals to character 'b'
        // we push back into the stream a 'B', which
        // would be read in the next iteration
        if (c == 'b') {
            is.unread((byte) 'B');
        }
    }
}

RandomAccessFile允许您读取流中特定偏移量的值。

foobBa

输出

try (RandomAccessFile ra = new RandomAccessFile("abc.txt", "r")) {
    // for demonstration we read only six values from the file
    for (int i = 0; i < 6; i++) {
        // read the next byte value from the stream
        int c = ra.read();
        // this is only for visualising the behavior
        System.out.print((char) c);
        // if the current read value equals to character 'b'
        // we move the file-pointer to offset 6, from which
        // the next character would be read
        if (c == 'b') {
            ra.seek(6);
        }
    }
}