Reputation: 37
I am creating a little program that will amend driver letters saved in a program file. The method works in the sense that it locates the file correctly and amends the drive letter correctly.
However when I open the file after it has been changed all the Directory listings are all on one line but they need to be 1 directory per line. I've tried saving each individual line to an Array List then printing them out like that but that didn't seem to work for me so was wondering if anyone could help?
Much appreciated.
P.S. Been messing around trying to make it work and also now ran into another issue where it is now printing them all out into one line but with spaces in between e.g:
S:\ D A T A\ S A G E\
public class copy
{
private String newDriveLetter;
private String line;
private Path[]sageFolders;
private FileReader fileReader;
private BufferedReader bufferedReader;
private FileWriter fileWriter;
private BufferedWriter bufferedWriter;
private List<String> lines = new ArrayList<String>();
public void scanFiles() throws IOException{
try
{
System.out.println("Sage 2015 is Installed on this machine");
File companyFile = new File(sageFolders[8] + "\\COMPANY");
fileReader = new FileReader(companyFile);
bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
if(line.contains("F"))
{
line = line.replace("F:\\","S:\\");
lines.add(line);
}
}
//Close the Readers
fileReader.close();
bufferedReader.close();
fileWriter = new FileWriter(companyFile);
bufferedWriter = new BufferedWriter(fileWriter);
for(String s : lines)
{
bufferedWriter.write(s);
}
bufferedWriter.flush();
bufferedWriter.close();
}
catch(FileNotFoundException e)
{
System.out.println("File not Found: Moving onto next Version");
}
}
Upvotes: 0
Views: 3350
Reputation: 93948
The problem is that readLine()
reads a whole line, and then tosses away the line ending. From the documentation:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So you have to add it back again, possibly using the preferred line ending for your platform:
bufferedWriter.write(String.format("%s%n", s);
here %s
is the String
and %n
is the platform dependent line ending.
Alternatively, as Ransom Briggs indicates, you may use newline()
. newLine()
is easier to read and will perform slightly better:
bufferedWriter.write(s);
bufferedWriter.newLine();
I've left the String.format
method in as it is a more general approach of adding newlines to strings.
Upvotes: 1
Reputation: 4820
Add this after bufferedWriter.write(s);:
bufferedWriter.write(System.getProperty("line.separator", "\n"));
This will add the system specific line separator, or "\n" if the system property is not set.
Upvotes: 0