Created
February 22, 2017 08:24
-
-
Save oguna/9a83c374bab0e505ceec044d571a9f3f to your computer and use it in GitHub Desktop.
テキストファイルの内容を行番号の情報とともに格納するJavaクラス
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.jetbrains.annotations.NotNull; | |
| import java.io.IOException; | |
| import java.nio.file.Files; | |
| import java.nio.file.Path; | |
| public class TargetFile { | |
| @NotNull | |
| public final String name; | |
| @NotNull | |
| public final String content; | |
| public TargetFile(@NotNull String name, @NotNull String content) { | |
| this.name = name; | |
| this.content = content; | |
| } | |
| public TargetFile(@NotNull Path path) throws IOException { | |
| this.name = path.toFile().toString(); | |
| this.content = new String(Files.readAllBytes(path)); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.jetbrains.annotations.NotNull; | |
| import java.io.IOException; | |
| import java.nio.file.Path; | |
| import java.util.Arrays; | |
| public class TargetFileWithLineNumber extends TargetFile { | |
| @NotNull | |
| private final int[] lineEnds; | |
| public TargetFileWithLineNumber(@NotNull String name, @NotNull String content) { | |
| super(name, content); | |
| this.lineEnds = getLineSeparators(this.content); | |
| } | |
| public TargetFileWithLineNumber(@NotNull Path path) throws IOException { | |
| super(path); | |
| this.lineEnds = getLineSeparators(this.content); | |
| } | |
| @NotNull | |
| private static int[] getLineSeparators(@NotNull String content) { | |
| int[] array = new int[256]; | |
| int index = 0; | |
| int pos = 0; | |
| while ((pos = content.indexOf('\n', pos)) != -1) { | |
| if (index - 1 >= array.length) { | |
| array = Arrays.copyOf(array, array.length * 2); | |
| } | |
| array[index++] = pos++; | |
| } | |
| return Arrays.copyOf(array, index); | |
| } | |
| public int getLineNumber(int i) { | |
| int index = Arrays.binarySearch(this.lineEnds, i); | |
| return index < 0 ? -index : index + 1; | |
| } | |
| public int getLineStart(int i) { | |
| return i == 1 ? 0 : this.lineEnds[i - 2] + 1; | |
| } | |
| public int getLineEnd(int i) { | |
| return this.lineEnds.length == i ? this.content.length() - 1 : this.lineEnds[i - 1]; | |
| } | |
| public int getLineSize() { | |
| return this.lineEnds.length; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment