java - 我如何将某些内容写入 .txt 文件,然后稍后将其复制为字符串或数组?
问题描述
我正在为学校做一个项目,让我自己研究语法和与该项目相关的其他事情。
我已经有了批量代码,这个想法是对居住在公寓楼、哪一层和哪个房间的人的索引。这也将节省租金/水电费。
我有办法将这些存储为多维数组。我不知道如何将代码复制到 .txt 文件中。
这是一个不使用数组的示例,例如
package buildings
public class main{
public static String name = "James";
public static int buildingName = 1;
public static int floor = 2;
public static int room = 1;
public static float rent = 250.99;
}
我怎么可能把这些变量放到一个文本文件中,以后再次运行程序时如何引用它们?
解决方案
这很简单,首先,您需要考虑存储变量的绝对格式。在这种情况下,对于数组,我使用它!var1!var2!var3
,然后使用特殊字符来表示数组中的下一行,例如,a ^ 所以像这样的二维数组
[0,0,0]
[1,2,3]
[4,5,6]
在文件中看起来像这样,0!0!0!^1!2!3!^4!5!6!
所以当你从包含这个的文件中读取
Scanner scanner = new Scanner( new File("src\\vars\\array1"));
String file = scanner.useDelimiter("\\A").next();
scanner.close();`
//you do
String[] arrays = file.split("^");`
//and then
String[][] test = new int[arrays.length][arrays.length];`
Assuming it's a square array, if
//not, just either remember how long it is or count throught the file first
for(int x = 0; x < arrays.length; x++)
test[x] = arrays[x].split("!");
//and then finally
int[][] finalArray = new int[test.length][test[0].length];
for(int x = 0; x < arrays.length; x++)
for(int y = 0; y < arrays.length; y++)
finalArray[x][y] = Integer.parseInt(test[x][y]);
并写入文件
File newfile = new File("src\\vars\\array1");
BufferedWriter out = new BufferedWriter(new FileWriter(newfile, true));
out.write("Print to the file using your format :)");`
对不起,代码括号中的整个事情,堆栈编辑器对我很生气。
推荐阅读
- hyperledger-fabric - Hyperledger Fabric 中的交易?
- qt - Qt.matrix4x4 和 QMatrix4x4 有什么区别?
- javascript - 获取参数对象以处理下划线 _.first 函数?
- javascript - 重定向到维护页面
- php - 三向枢轴表 Laravel
- python - 如何提高python exe文件的速度?
- node.js - 节点使用变量内容执行shell命令
- swift - 长 RTL 文本在 SwiftUI 中被截断/溢出
- oauth - 使用给定令牌向 Twitch API 进行身份验证
- sql - 如何在'where'子句中使用laravel查询构建器中的括号?