在下面的代码中,我试图检查用户输入的路径是否正确。如果输入的路径正确且正确,则下面的代码行将尝试使用BufferedReader打开该特定文件,读取该文件的内容,然后将内容传递回另一个函数以进行进一步处理。
示例:文件路径为“ C:\ Desktop \ A.txt”,并且A.txt包含ABCD EFGH,则“ ABCD EFGH”将被传递回调用函数(即,调用文件内容的函数如下所示)
目前,以下代码正在传回“ ABCD EFGH”。但是,它以以下方式通过:[ABCD EFGH]。无论如何,是否有必要删除括号并仅以ABCD EFGH的形式传递字符串
public static void main(String[] args) throws FileNotFoundException
{
Sample();
}
public static void Sample ()
{
String filename = "C:\\Desktop\\A.txt";
//This will call filecontents function - Value returned from filecontents function will be stored in 'content'
List<String> content = filecontents (filename);
//Converting List String to String since my next function accepts Strings only and not List<String>
String[] strarray = content.toArray(new String[0]);
String Statement = (Arrays.toString(strarray));
System.out.println("X:"+Statement);
}
private static List<String> filecontents(String file)
{
Path path = Paths.get(file);
if (Files.exists(path))
{
List<String> records = new ArrayList<String>();
try
{
//Open the text file
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null)
{
records.add(line);
}
for (String s : records)
System.out.println("Record:"+s);
reader.close();
return records;
}
catch (Exception e)
{
System.err.format("Exception occurred trying to read '%s'.", file);
e.printStackTrace();
}
} else
{
System.out.println("Filename is not correct. Exiting.");
}
return null;
}