-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
NioTextFile.java
101 lines (83 loc) · 2.71 KB
/
NioTextFile.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.internal.util.AssertionUtil;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.util.IOUtil;
import net.sourceforge.pmd.util.datasource.DataSource;
import net.sourceforge.pmd.util.datasource.FileDataSource;
import net.sourceforge.pmd.util.datasource.internal.LanguageAwareDataSource;
/**
* A {@link TextFile} backed by a file in some {@link FileSystem}.
*/
@Experimental
class NioTextFile implements TextFile {
private final Path path;
private final Charset charset;
private final LanguageVersion languageVersion;
private final String displayName;
private final String pathId;
NioTextFile(Path path, Charset charset, LanguageVersion languageVersion, String displayName) {
AssertionUtil.requireParamNotNull("path", path);
AssertionUtil.requireParamNotNull("charset", charset);
AssertionUtil.requireParamNotNull("language version", languageVersion);
this.displayName = displayName;
this.path = path;
this.charset = charset;
this.languageVersion = languageVersion;
this.pathId = path.toAbsolutePath().toString();
}
@Override
public LanguageVersion getLanguageVersion() {
return languageVersion;
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
public String getPathId() {
return pathId;
}
@Override
public String readContents() throws IOException {
if (!Files.isRegularFile(path)) {
throw new IOException("Not a regular file: " + path);
}
try (BufferedReader br = Files.newBufferedReader(path, charset)) {
return IOUtil.readToString(br);
}
}
@Override
public DataSource toDataSourceCompat() {
return new LanguageAwareDataSource(new FileDataSource(path.toFile()), languageVersion);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NioTextFile that = (NioTextFile) o;
return Objects.equals(path, that.path);
}
@Override
public int hashCode() {
return Objects.hash(pathId);
}
@Override
public String toString() {
return getPathId();
}
}