我想从"Hello"
文件中读取文本,然后我想将此文本转换为相应的二进制形式,如:
01001000 01100101 01101100 01101100 01101111
现在,我进行二进制转换后,我想再次转换相同的
01001000 01100101 01101100 01101100 01101111
到Hello
并将其写入文件
如何对“Hello World my name is XYZ”这样的多个单词做同样的事情
我怎么可能这样做?请帮忙
答案 0 :(得分:1)
我没有详细介绍如何读/写文件,因为你可以查看一下。但是,要实现你想要的目标:
下面是代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args) throws FileNotFoundException {
File file = new File("input.txt");
Scanner sc = new Scanner(file);
String word=sc.nextLine();
String receivedBinary=stringToBinary(word);
System.out.println();
String receivedWord=BinaryToString(receivedBinary);
}
public static String stringToBinary(String text)
{
String bString="";
String temp="";
for(int i=0;i<text.length();i++)
{
temp=Integer.toBinaryString(text.charAt(i));
for(int j=temp.length();j<8;j++)
{
temp="0"+temp;
}
bString+=temp+" ";
}
System.out.println(bString);
return bString;
}
public static String BinaryToString(String binaryCode)
{
String[] code = binaryCode.split(" ");
String word="";
for(int i=0;i<code.length;i++)
{
word+= (char)Integer.parseInt(code[i],2);
}
System.out.println(word);
return word;
}
}
答案 1 :(得分:0)
toBitgets
来打印一个字节的所有8位。
这个类还使用了一些正则表达式来确保解析后的字符串具有所请求的精确表示:8位,后跟空格或输入的结尾。
import static java.nio.charset.StandardCharsets.US_ASCII;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class S2B2S {
public S2B2S() {
}
public void toBitgets(StringBuilder sb, byte b) {
for (int i = 0; i < Byte.SIZE; i++) {
sb.append('0' + ((b >> (Byte.SIZE - i - 1))) & 1);
}
}
public String encode(String s) {
byte[] sdata = s.getBytes(US_ASCII);
StringBuilder sb = new StringBuilder(sdata.length * (Byte.SIZE + 1));
for (int i = 0; i < sdata.length; i++) {
if (i != 0) {
sb.append(' ');
}
byte b = sdata[i];
toBitgets(sb, b);
}
return sb.toString();
}
public String decode(String bs) {
byte[] sdata = new byte[(bs.length() + 1) / (Byte.SIZE + 1)];
Pattern bytegets = Pattern.compile("([01]{8})(?: |$)");
Matcher bytegetsFinder = bytegets.matcher(bs);
int offset = 0, i = 0;
while (bytegetsFinder.find()) {
if (bytegetsFinder.start() != offset) {
throw new IllegalArgumentException();
}
sdata[i++] = (byte) Integer.parseInt(bytegetsFinder.group(1), 2);
offset = bytegetsFinder.end();
}
if (offset != bs.length()) {
throw new IllegalArgumentException();
}
return new String(sdata, US_ASCII);
}
public static void main(String[] args) {
String hello = "Hello";
S2B2S s2b2s = new S2B2S();
String encoded = s2b2s.encode(hello);
System.out.println(encoded);
String decoded = s2b2s.decode(encoded);
System.out.println(decoded);
}
}