I am somewhat new to java and was hoping that someone could help me. I have looked everywhere, but cannot seem to finder a solution.
I’m trying to save the result of a method into a file using bufferedwriter. The bufferedwriter itself works as it is saving some other strings, but when it comes to this function is just displays ‘null’. Is is because the result of this method returns more than one string? How do I resolve this?
My code is as following:
Bufferedwriter code:
public static boolean saveStringToFile (String fileName, String saveString)
{
boolean saved = false;
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new FileWriter(fileName));
try
{
bw.write(saveString);
saved = true;
}
finally
{
bw.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
return saved;
}
The function itself:
public static void getNetDetails()
{
try {
Process net = Runtime.getRuntime().exec("lsof -i -n -P");
BufferedReader netInput = new BufferedReader(
new InputStreamReader(net.getInputStream()));
while ((netDetails = netInput.readLine()) !=null)
{
System.out.println(netDetails);
System.out.println("\n");
}
}
catch(IOException e) {
System.out.println("exception happened - here are the details: ");
e.printStackTrace();
}
}
Saving function to file using bufferedwriter
public static void generateNetReport()
{
saveStringToFile("Net.txt","here is the thing.." + "\n" + netDetails );
}
can someone please help with how I can save netDetails onto a file without it just displaying null??
(Edited.)
This is the problem, in
getNetDetails():In other words, the method will always leave
netDetailsas null, unless there’s an exception.It would be better if
getNetDetails()returned a string instead of setting a variable, and assuming it’s meant to return the final line of the file, it should be something like:You should also close the
InputStreamReaderin a finally block, and almost certainly not swallow the exception.