0

I have a .txt file named "new.txt" and its content is;

nxy15\nxy995\nxy823\nxy721\nxy1\nxy1872\nxy3482\nxy878\nxy123\nxy8753\nxy1284\nxy4495\nxy4323\nxy812\nxy7123\nxy1273

I need to format that .txt file, to be more specific i need to go to the next line when backslash is detected like one number for each line and i need to remove the letters aswell.

Formatted .txt file needs to look like this;

15
995
823
721
1
1872
...

So far, because of my little Java knowledge, i managed to just read the file and output it. Here it is;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingFile{
    public static void main(String[] args) {
        try {
            File file = new File("C:\\new.txt");
            Scanner read = new Scanner(file);
            while (read.hasNextLine()) {
                String obj2 = read.nextLine();
                System.out.println(obj2);
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

I need to solve this so i can move on to the next question but i'm stuck with this question and can't solve it and i'm trying for three hours.

Any help or clues are highly appreciated, thanks.

  • [Split the string](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java), then for each element of the resulting array remove the letters and print the remaining digits, one element per line. – Federico klez Culloca May 29 '20 at 16:32
  • 3
    @Jackiejack764 You describe this as being part of a test or series of questions. Is it within the rules of the test/series of questions (and school/educational facility/similar if applicable) to ask others for help? – MelvinWM May 29 '20 at 16:35
  • @MelvinWM It is not a question in any kind of particular school or in educational facility (in my knowledge) and i'm only asking for my own progress in Java. – Jackiejack764 May 29 '20 at 16:51
  • I'm assuming that the letters will always be `nxy`? – Nosrep May 29 '20 at 16:57
  • @Jackiejack764 If so, then I wonder if it would be better for you to get guides and tips on how to do it, instead of solutions. I don't know how well you know programming in general; in case you are new to it, I would recommend first looking at the question again and ensure that the input file in the question really has a single line with `\n` in it. In case you aren't aware of it, `\n` is a common newline escape sequence. See more for instance here: https://en.wikipedia.org/wiki/Newline#Representation . – MelvinWM May 29 '20 at 17:04

5 Answers5

1

Just put this to your string:

String obj2 = read.nextLine().replace("\\", "\n"); 

It will print a new line each time it finds \

Balastrong
  • 4,336
  • 2
  • 12
  • 31
0

You should try reading the original text file in, splitting around "/", and then printing each line of the resultant array

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingFile{
    public static void main(String[] args) {
        FileWriter myWriter = new FileWriter("filename.txt");
        try {
            File file = new File("C:\\new.txt");
            Scanner read = new Scanner(file);
            while (read.hasNext()) {
                String obj2 = read.next();
                String[] arr = obj2.split("\");
                for(String s : arr) {
                    myWriter.write(s);
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
        myWriter.close()
    }
}
willturner
  • 104
  • 6
0

Try like this:

String s = "nxy15\nxy995\nxy823\nxy721\nxy1\nxy1872\nxy3482\nxy878\nxy123\nxy8753\nxy1284\nxy4495\nxy4323\nxy812\nxy7123\nxy1273";
String[]s1 = s.split("[\\\\]+");
for(String s2:s1) {
    System.out.println(s2.replaceAll("[A-Za-z]", ""));
}

You'll get:

15
995
823
721
1
1872
3482
878
123
8753
1284
4495
4323
812
7123
1273
Arun
  • 785
  • 8
  • 13
0

A functional way of doing it (since Java 8) would be something like:

Files.lines(Paths.get("C:\\new.txt"))
                .flatMap(s -> Arrays.stream(s.split("\\\\")))
                .map(s -> s.substring(3))
                .forEach(System.out::println);

If you want to sink the results into another file you can drop the forEach and feed the stream into a Files.write:

Files.write(Paths.get("C:\\formatted.txt"),
            Files.lines(Paths.get("C:\\new.txt"))
                .flatMap(s -> Arrays.stream(s.split("\\\\")))
                .map(s -> s.substring(3)).collect(Collectors.toList()));

Please note that this is not contemplating possible input errors (e.g. different format in the string nxy123), but that should not be difficult to add.

rph
  • 2,104
  • 2
  • 13
  • 24
0

This is how I would do it:

public class ReadingFile{
    public static void main(String[] args) {
        File in = new File("C:\\old.txt");
        File out = new File("C:\\new.txt");
        ArrayList<String> al = new ArrayList<>();

        try (Scanner read = new Scanner(in);
                FileWriter write = new FileWriter(out)) { //ALWAYS use try-with-resources if you can
            while (read.hasNextLine()) {
                al.add(read.nextLine()); //reads to an ArrayList (so there could be multiple lines in the input file)
            }

            for (String str : al) {
                write.write(str.replace("\\", "\n")); //replace all backslashes with newlines
                write.write('\n');
            }

            write.flush(); //flush the Writer at the end, so everything gets written to the file
        } catch (FileNotFoundException e) {
            throw new RuntimeException("File not found."); //Don't swallow exceptions, at least throw a RuntimeException
        } catch (IOException ex) {
            throw new RuntimeException("IO exception occured"); //Don't swallow exceptions, at least throw a RuntimeException
        }
    }
}
Charlie Armstrong
  • 2,332
  • 3
  • 13
  • 25