gpt4 book ai didi

java - 将二维字符串数组保存在 .text 文件中并从中加载

转载 作者:行者123 更新时间:2023-12-02 11:27:20 32 4
gpt4 key购买 nike

我想将二维字符串数组保存在 .txt 文件中,并将其加载到我的应用程序中。该数组应该可以在应用程序中编辑和扩展。我对 BufferedWriter、BufferedReader、FileInputStream 和 FileOutputStream 之类的东西并没有真正的经验。我对这段代码有问题: BufferedWriter 和 BufferedReader 抛出 NullPointerException,我不知道为什么。或者每个人都知道使用 FileInputStream 和 FileoutputStream 执行此操作的可能性吗?

public String path = 
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFile";
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(path + "/savedFile.txt");

public static void Save(File file, String[][] list)
{
BufferedWriter writer = null;
StringBuilder builder = new StringBuilder();
try
{
writer = new BufferedWriter(new FileWriter(file));
}
catch (IOException e) {e.printStackTrace();}
try
{
try
{
for(int i = 0; i < list.length; i++)
{
for(int j = 0; j < list[i].length; j++)
{
builder.append(list[i][j]+"");
if(j < list.length - 1)
builder.append(",");
}
builder.append("\n");
}
}
catch (Exception e) {e.printStackTrace();}
}
finally
{
try
{
writer.write(builder.toString());
writer.close();
}
catch (IOException e) {e.printStackTrace();}
}
}


public static String[][] Load(File file)
{
BufferedReader reader = null;

try
{
reader = new BufferedReader(new FileReader(file));
}
catch (FileNotFoundException e) {e.printStackTrace();}
String test;

String[][] array = new String[4][2]; //the indexs are for a specific example; it should be expandable, but I solve that myself

String line;
int row = 0;
try
{
while ((line = reader.readLine()) != null) {
String[] cols = line.split(",");
int col = 0;
for (String c : cols) {
array[row][col] = c;
col++;
}
row++;
}
}
catch (IOException e) {e.printStackTrace();}
return array;
}

最佳答案

我认为问题出在您使用的多个大括号中的变量范围。试试这个代码:

    public static void Save(File file, String[][] list) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < list.length; i++) {
for (int j = 0; j < list[i].length; j++) {
builder.append(list[i][j] + "");
if (j < list.length - 1) {
builder.append(",");
}
}
builder.append("\n");
}

try {
Writer writer = new BufferedWriter(new FileWriter(file));
try {

writer.write(builder.toString());
} finally {
writer.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

关于java - 将二维字符串数组保存在 .text 文件中并从中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49520027/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com