Reputation: 93
Im trying to remove all commas from my text file, where am i going wrong? I think its to do with the replaceAll field, ive done research into it, but cannot find any answers. I also need there to be a new line after a ";" as well as removing the commas. Thankyou in advance
`public static void open(){
// The name of the file to open.
String fileName = "Test.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
line.replaceAll(",","\\.");
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
}`
Upvotes: 2
Views: 1788
Reputation: 39
Try to load file with :
public static String readAllText(String filename) throws Exception {
StringBuilder sb = new StringBuilder();
Files.lines(Paths.get(filename)).forEach(sb::append);
return sb.toString();
}
then change what do you want.
String file = readAllText("myfile.txt");
file = file.replace(",","\\.);
Upvotes: 0
Reputation: 121
changing line.replaceAll(",","\\.");
to line = line.replaceAll(",","\\.");
should fix your problem.
As for putting newlines after ";" use line = line.replaceAll(";",";\n");
Upvotes: 0
Reputation: 472
Strings are immutable in Java, so System.out.println(line.replaceAll(",","\\."))
is what you want. You want to print the returned value.
Upvotes: 1
Reputation: 172408
You may try like this:
String s = line.replaceAll(",","\\.");
Note Java strings are immutable
or you may choose to directly print it as:
System.out.println(line.replaceAll(",","\\."));
In you code when you say:
line.replaceAll(",","\\.");
then there is no change in the line and it returns a new String.
Upvotes: 0
Reputation: 3302
line.replaceAll(",","\\.");
Java Strings are immutable - this does not alter line
but returns a new String with the desired replacement applied. Try assigning that to a variable instead:
String s = line.replaceAll(",","\\.");
or printing it directly:
System.out.println(line.replaceAll(",","\\."));
Upvotes: 0