我有一个包含“二进制”的文本文件,它只是一长串二进制数字,将代表接下来的汇编指令。目前我想做的就是将这一长串二进制数字加载到 String[]
中,一次包含 8 个字符。
例如:
0000000100000002000000030000000400000005000000060000000700000008
将读作:
[0] 000000001
[1] 000000002
[2] 000000003
[3] 000000004
[4] 000000005
[5] 000000006
[6] 000000007
[7] 000000008
我现在可以考虑执行此操作的唯一方法是读取整个字符串并将其存储在 String
变量中,然后一次迭代变量 8 个字符并使用 substring()
将大字符串分割成较小的 8 个字符字符串。
肯定有更有效的方法来做到这一点吗?
最佳答案
您可以使用 Alan Moore 在 this 中提供的正则表达式答案,如果您更喜欢 Java 8 解决方案,您可能需要考虑使用
Stream
:String str = "0000000100000002000000030000000400000005000000060000000700000008"; List<String> list = (Stream.of(str.split("(?<=\\G.{8})")) .collect(Collectors.toList())); // Result of splitting input String is stored in a List String[] strings = list.toArray(new String[list.size()]); // Create an array from contents of list System.out.println(Arrays.toString(strings)); // print result array to console
如果您不允许使用 Java 8 功能,您可以使用
String
类中提供的方法substring()
:String str = "0000000100000002000000030000000400000005000000060000000700000008"; ArrayList<String> list = new ArrayList<>(); // To store results of cutting input String while(str.length() != 0) { // Until you reach end of String... list.add(str.substring(0, 8)); // Add first eight characters of input String str = str.substring(8, str.length()); // Cut input String to leave only characters not added to list in previous line } String[] array = list.toArray(new String[list.size()]); // Create a String[] and add contents of ArrayList to it System.out.println(Arrays.toString(array)); // Print result String[]
在这两种情况下得到的输出:
[00000001, 00000002, 00000003, 00000004, 00000005, 00000006, 00000007, 00000008]
关于java - 如何读取 .txt 文件并每 8 个字符分割一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48390698/