If I print directly as
System.out.println("a\nb");
the result will be as expected, with a new line between characters,
but if I read the same line from a text file using
public static void main(String[] args) throws IOException {
List<String> lines;
lines = Files.readAllLines(Paths.get("filename.txt"));
String[] array = lines.toArray(new String[0]);
System.out.println(array[0]);
the text displayed will be exactly as written in a file "a\nb" without a new line between the characters. toString and other methods do not help.
How should I update the code?
With the help of the colleagues and commenters got an explanation and an answer (not the most elegant approach though).
"\n" in the code is interpreted as a new line character, but when read from a file it becomes a set of two characters: "\" and "n" and is no longer properly recognized. The shortest way to eliminate the problem would be to replace these characters with the new line in the code of the program, adding "replace("\n", "\n")". So, the code becomes as follows:
public static void main(String[] args) throws IOException {
List<String> lines;
lines = Files.readAllLines(Paths.get("filename.txt"));
String[] array = lines.toArray(new String[0]);
System.out.println(array[0].replace("\\n", "\n"));
Related
Hi guys I'm writing a method which counts words in a file, but apparently there is a mistake somewhere in the code and the method does not work. Here's my code:
public class Main2 {
public static void main(String[] args) {
count("/home/bruno/Desktop/WAR_JEE_S_09_Podstawy/MojPlik");
}
static int count(String fileName){
Path path = Paths.get(fileName);
int ilosc = 0;
String wyjscie = "";
try {
for (String charakter : Files.readAllLines(path)){
wyjscie += charakter;
}
StringTokenizer token = new StringTokenizer(wyjscie," \n");
} catch (IOException e) {
e.printStackTrace();
}
return ilosc;
}
}
The file path is correct, here is the file content
test test
test
test
after i call the method in main it displays nothing. Where is the mistake ?
Your code would count lines in a file ... well, if you followed up on that thought.
Right ow your code is simply reading lines, putting them into one large string, to then do nothing about the result of that operation. You have a single int counter ... who is init'ed to 0, and then just returned without ever being used/increased! And unless I am mistaken, readAllLines() will automatically remove the newline char in the end, so overall, your code is nothing but useless.
To count words you have to take each line and (for example) split that one-line-string for spaces. That gives you a number. Then add up these numbers.
Long story short: the real answer here is that you should step back. Don't just write code, assuming that this will magically solve the problem. Instead: first think up a strategy (algorithm) that solves the problem. Write down the algorithm ideas using a pen and paper. Then "manually" run the algorithm on some sample data. Then, in the end, turn the algorithm into code.
Also, beside that you does not output anything, there is a slight error behind you logic. I have made a few changes here and there to get your code working.
s.trim() removes any leading and trainling whitespace, and trimmed.split("\\s+") splits the string at any whitespace character, including spaces.
static int count(String fileName) throws IOException {
Path path = Paths.get(fileName);
int count = 0;
List<String> lines = Files.readAllLines(path);
for (String s : lines) {
String trimmed = s.trim();
count += trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;
}
return count;
}
Here is the code using functional-style programming in Java 8. This is also a common example of using Stream's flatMap - may be used for counting or printing words from a file.
long n = Files.lines(Paths.get("test.txt"))
.flatMap(s -> Stream.of(s.split("\\s+")))
.count();
System.out.println("No. of words: " + n);
Note the Files.lines(Path) returns a Stream<String> which has the lines from the input file. This method is similar to readAllLines, but returns a stream instead of a List.
I'm coding in Java and I want to split my string. I want to split it at.
/* sort */
Yes I plan to split a .java file that I have read as a string so I need it to include "/* sort */". I'm creating a code that sorts Arrays that are predefined in java class file.
Exactly that and do another split at
}
and then I wanted help how to go about splitting up the array since I'll be left with
an example would be this
final static String[] ANIMALS = new String[] /* sort */ { "eland", "antelope", "hippopotamus"};
My goal would be to sort that Array inside a .java file and replace it. This is my current code
private void editFile() throws IOException {
//Loads the whole Text or java file into a String
try (BufferedReader br = new BufferedReader(new FileReader(fileChoice()))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
}
arrayCutOff = everything.split("////* sort *////");
for(int i = 0; i < arrayCutOff.length; i++){
System.out.println(arrayCutOff[i]);
}
}
This basically reads the whole .txt or .java file completely with the exact same formatting into one string. I planned to split it at /* sort */ and sort the array inside but I realized if I did that I probably can't replace it.
Considered your're using java 8 you might go this direction:
private void editFile() throws IOException {
List<String> lines = Files.readAllLines(Paths.get(fileChoice()));
String content = lines.stream().collect(Collectors.joining(System.lineSeparator()));
Stream.of(content.split(Pattern.quote("/* sort */"))).forEach(System.out::println);
}
However, the trick you're asking for is Pattern.quote, which dates back Java 5. It'll qoute a literal so it can be used as a literal in regExs and is a bit more convenient (and reliable I think) than wrestling around with backslashes...
I am trying to see if a string in my array matches a word. If so, perform the If statement.
Sounds simple as pie but the If statement does not see the string from the array!
The array (temps) contains nothing but "non"s so I know it's something wrong with the If statment.
Here is the snippet of code:
if ("non".equals(temps.get(3))) {
System.out.println("Don't know.");
}
Where temps is the array containing "non"s on different lines.
Here is the full code in case anyone is wondering:
public class Dump {
public static void main(String[] args) throws IOException {
String token1 = "";
//Reads in presidentsUSA.txt.
Scanner inFile1 = new Scanner(new File("presidentsUSA.txt"));
//Splits .txt file via new lines.
inFile1.useDelimiter("\\n");
List<String> temps = new ArrayList<String>();
while (inFile1.hasNext()) {
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
// Stores each new line into an array called temps.
String[] tempsArray = temps.toArray(new String[0]);
if ("non".equals(temps.get(3))) {
System.out.println("Don't know.");
}
}
}
The most probable explanation why your if statement returns false is that you are on a Windows OS.
If you debug your code and watch temps.get(3) it will show the content as
non\r
and non\r does not equal non
Solution:
inFile1.useDelimiter("\\r\\n");
Check the accepted answere here (especially point 4): Difference between \n and \r?
This question already has answers here:
How to compare two Strings in java without considering spaces?
(9 answers)
Closed 7 years ago.
I want to create a Unit test method. Version of Java - 1.6
#Test
public void TestCreateHtml() throws IOException{
final File output = parser.createHtml();
final File expected = new File("src/main/resources/head.jsp");
assertEquals("The files differ!", FileUtils.readLines(expected), FileUtils.readLines(output));
}
This test method doesn't work.
The contents of both files are equals, but they have different number of white spaces.
How can I ignore the white spaces?
If the problem is in leading/trailing white space:
assertEquals(actual.trim(), expected.trim());
If problem is in file contents, only solution I can think of is to remove all white space from both inputs:
assertEquals(removeWhiteSpaces(actual), removeWhiteSpaces(expected));
where removeWhiteSpaces() method looks like this:
String removeWhiteSpaces(String input) {
return input.replaceAll("\\s+", "");
}
If the problem is only leading/trailing white spaces, you can compare line by line after trimming both. This does not work if there can also be extra newlines in one file compared to the other.
#Test
public void TestCreateHtml() throws IOException{
final File output = parser.createHtml();
final File expected = new File("src/main/resources/head.jsp");
List<String> a = FileUtils.readLines(expected);
List<String> b = FileUtils.readLines(output);
assertEquals("The files differ!", a.size(), b.size());
for(int i = 0; i < a.size(); ++i)
assertEquals("The files differ!", a.get(i).trim(), b.get(i).trim());
}
Iterate over list and trim each line
List<String> result = new ArrayList<String>();
for(String s: FileUtils.readLines(expected)) {
result.add(s.trim());
}
Same with other file.
And then compare new lists.
Just remove the leading and trailing whitespace before comparing:
#Test
public void TestCreateHtml() throws IOException{
final File output = parser.createHtml();
final File expected = new File("src/main/resources/head.jsp");
assertEquals("The files differ!", FileUtils.readLines(expected).replaceAll("^\\s+|\\s+$", ""), FileUtils.readLines(output).replaceAll("^\\s+|\\s+$", ""));
}
I have some text files with time information, like:
46321882696937;46322241663603;358966666
46325844895266;46326074026933;229131667
46417974251902;46418206896898;232644996
46422760835237;46423223321897;462486660
For now, I need the third column of the file, to calculate the average.
How can I do this? I need to get every text lines, and then get the last column?
You can read the file line by line using a BufferedReader or a Scanner, or even some other techinique. Using a Scanner is pretty straightforward, like this:
public void read(File file) throws IOException{
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
System.out.println(scanner.nextLine());
}
}
For splitting a String with a defined separator, you can use the split method, that recevies a Regular Expression as argument, and splits a String by all the character sequences that match that expression. In your case it's pretty simple, just the ;
String[] matches = myString.split(";");
And if you want to get the last item of an array you can just use it's length as parameter. remembering that the last item of an array is always in the index length - 1
String lastItem = matches[matches.length - 1];
And if you join all that together you can get something like this:
public void read(File file) throws IOException{
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
String[] tokens = scanner.nextLine().split(";");
String last = tokens[tokens.length - 1];
System.out.println(last);
}
}
Yes you have to read each line of the file and split it by ";" separator and read third element.