common-utils/src/main/java/org/warp/commonutils/serialization/UTFUtils.java

43 lines
1.1 KiB
Java
Raw Normal View History

2020-06-12 18:36:36 +02:00
package org.warp.commonutils.serialization;
import java.io.DataInput;
import java.io.DataOutput;
2020-06-12 18:36:36 +02:00
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class UTFUtils {
2021-08-24 11:23:39 +02:00
public static void writeUTF(DataOutput out, String utf) throws IOException {
2020-06-12 18:36:36 +02:00
byte[] bytes = utf.getBytes(StandardCharsets.UTF_8);
out.writeInt(bytes.length);
out.write(bytes);
}
2021-08-24 11:23:39 +02:00
public static String readUTF(DataInput in) throws IOException {
2020-06-12 18:36:36 +02:00
int len = in.readInt();
byte[] data = new byte[len];
in.readFully(data, 0, len);
return new String(data, StandardCharsets.UTF_8);
2020-06-12 18:36:36 +02:00
}
2021-08-24 11:23:39 +02:00
/**
* Keep only ascii alphanumeric letters
*/
public static String keepOnlyASCII(String nextString) {
char[] chars = nextString.toCharArray();
//noinspection UnusedAssignment
nextString = null;
int writeIndex = 0;
char c;
for (int checkIndex = 0; checkIndex < chars.length; checkIndex++) {
c = chars[checkIndex];
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
if (writeIndex != checkIndex) {
chars[writeIndex] = c;
}
writeIndex++;
}
}
return new String(chars, 0, writeIndex);
}
2020-06-12 18:36:36 +02:00
}