gpt4 book ai didi

JAVA : file I/O

转载 作者:行者123 更新时间:2023-11-30 08:12:56 25 4
gpt4 key购买 nike

我有两个文本文件,其数据格式如下

data.txt 文件格式如下

A 10
B 20
C 15

data1.txt 文件格式(起始节点、结束节点、距离):

A B 5 
A C 10
B C 20

我正在尝试实现搜索策略,因为我需要从 data.txt 加载数据,并且仅从 data1.txt 加载起始节点和结束节点(即我不需要距离)。我需要将这些信息存储在堆栈中,因为我认为这将是实现贪婪搜索的最佳数据结构。

实际上我不知道如何开始使用文件 I/O 来读取这些文件并将它们存储在数组中以实现贪婪搜索。因此,我非常感谢任何有关如何进行的起始想法。

我是新手,所以请耐心等待。任何帮助深表感谢。谢谢。

编辑:这是我到目前为止所得到的

String heuristic_file = "data.txt";
try
{

FileReader inputHeuristic = new FileReader(heuristic_file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;

while ((line = bufferReader.readLine()) != null)
{
System.out.println(line);
}

bufferReader.close();

} catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}

最佳答案

我的方法与其他人没有本质上的不同。请注意 try/catch/finally block 。始终将关闭语句放入finally block 中,这样即使在读取文件时抛出异常,也保证打开的文件被关闭。

两个//[...] 之间的部分肯定可以做得更有效。也许一次性读取整个文件,然后向后解析文本并搜索换行符?也许Stream-API支持设置读取位置。老实说我不知道​​。到目前为止我还不需要这个。

我选择使用 BufferedReader 的详细初始化,因为这样您就可以指定文件的预期编码。在你的情况下,这并不重要,因为你的文件不包含标准 ASCII 范围之外的符号,但我相信这是一个半最佳实践。

在你问之前:r.close()负责以正确的顺序关闭底层的InputStreamReaderFileInputStream,直到所有读者并且流被关闭。

public static void readDataFile(String dir, String file1, String file2)
throws IOException
{
File datafile1 = new File(dir, file1);
File datafile2 = new File(dir, file2);

if (datafile1.exists())
{
BufferedReader r = null;

try
{
r = new BufferedReader(
new InputStreamReader(
new FileInputStream(datafile1),
"UTF-8"
)
);

String row;

Stack<Object[]> s = new Stack<Object[]>();
String[] pair;
Integer datapoint;

while((row = r.readLine()) != null)
{
if (row != null && row.trim().length() > 0)
{
// You could use " " instead of "\\s"
// but the latter regular expression
// shorthand-character-class will
// split the row on tab-symbols, too
pair = row.split("\\s");
if (pair != null && pair.length == 2)
{
datapoint = null;
try
{
datapoint = Integer.parseInt(pair[1], 10);
}
catch(NumberFormatException f) { }

// Later you can validate datapairs
// by using
// if (s.pop()[1] != null)
s.add(new Object[] { pair[0], datapoint});
}
}
}
}
catch (UnsupportedEncodingException e1) { }
catch (FileNotFoundException e2) { }
catch (IOException e3) { }
finally
{
if (r != null) r.close();
}
}

// Do something similar with datafile2
if (datafile2.exists())
{
// [...do the same as in the first try/catch block...]

String firstrow = null, lastrow = null;
String row = null;
int i = 0;
do
{
lastrow = row;
row = r.readLine();
if (i == 0)
firstrow = row;
i++;
} while(row != null);

// [...parse firstrow and lastrow into a datastructure...]
}
}

关于JAVA : file I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30104347/

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