FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/CoreJava/v2ch06/textFormat/IPAddressFormatter.java at master · mthli/Java · GitHub
mthli
/
Java
Public
Notifications
You must be signed in to change notification settings
Fork
78
Star
137
Code
Issues
2
Pull requests
1
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
CoreJava
/
v2ch06
/
textFormat
/
IPAddressFormatter.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
50 lines (47 loc) · 1.47 KB
Breadcrumbs
Java
/
CoreJava
/
v2ch06
/
textFormat
/
IPAddressFormatter.java
Copy path
File metadata and controls
50 lines (47 loc) · 1.47 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
textFormat
;
import
java
.
text
.*;
import
java
.
util
.*;
import
javax
.
swing
.
text
.*;
/**
* A formatter for 4-byte IP addresses of the form a.b.c.d
*/
public
class
IPAddressFormatter
extends
DefaultFormatter
{
public
String
valueToString
(
Object
value
)
throws
ParseException
{
if
(!(
value
instanceof
byte
[]))
throw
new
ParseException
(
"Not a byte[]"
,
0
);
byte
[]
a
= (
byte
[])
value
;
if
(
a
.
length
!=
4
)
throw
new
ParseException
(
"Length != 4"
,
0
);
StringBuilder
builder
=
new
StringBuilder
();
for
(
int
i
=
0
;
i
<
4
;
i
++)
{
int
b
=
a
[
i
];
if
(
b
<
0
)
b
+=
256
;
builder
.
append
(
String
.
valueOf
(
b
));
if
(
i
<
3
)
builder
.
append
(
'.'
);
}
return
builder
.
toString
();
}
public
Object
stringToValue
(
String
text
)
throws
ParseException
{
StringTokenizer
tokenizer
=
new
StringTokenizer
(
text
,
"."
);
byte
[]
a
=
new
byte
[
4
];
for
(
int
i
=
0
;
i
<
4
;
i
++)
{
int
b
=
0
;
if
(!
tokenizer
.
hasMoreTokens
())
throw
new
ParseException
(
"Too few bytes"
,
0
);
try
{
b
=
Integer
.
parseInt
(
tokenizer
.
nextToken
());
}
catch
(
NumberFormatException
e
)
{
throw
new
ParseException
(
"Not an integer"
,
0
);
}
if
(
b
<
0
||
b
>=
256
)
throw
new
ParseException
(
"Byte out of range"
,
0
);
a
[
i
] = (
byte
)
b
;
}
if
(
tokenizer
.
hasMoreTokens
())
throw
new
ParseException
(
"Too many bytes"
,
0
);
return
a
;
}
}
Back
|
FazBrowse Home
|
New Git URL