作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将二维字符串数组保存在 .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/
我是一名优秀的程序员,十分优秀!