我需要将 .txt 文件的内容在遇到反斜杠时拆分到新行。

huangapple go评论137阅读模式
英文:

I need to split .txt file's content to a new line when it sees a backslash

问题

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();
                String[] numbers = obj2.split("xy");
                for (String number : numbers) {
                    if (!number.isEmpty()) {
                        System.out.println(number);
                    }
                }
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Please let me know if you need further assistance or have any questions.

英文:

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.

答案1

得分: 1

只需将此内容添加到您的字符串中:

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

每次找到 \ 时,它都会打印一个新行。

英文:

Just put this to your string:

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

It will print a new line each time it finds \

答案2

得分: 0

你应该尝试读取原始文本文件围绕着/进行分割然后打印结果数组的每一行

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();
    }
}
英文:

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()
    }
}

答案3

得分: 0

尝试这样写:

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]", ""));
}
英文:

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

答案4

得分: 0

使用函数式编程的方式自Java 8起可以这样实现

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

如果你想将结果写入另一个文件,你可以去掉 forEach 并将流传递给 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()));

请注意,这并未考虑可能的输入错误(例如字符串 nxy123 的不同格式),但是添加这些处理应该不难。


<details>
<summary>英文:</summary>

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

```java
Files.lines(Paths.get(&quot;C:\\new.txt&quot;))
                .flatMap(s -&gt; Arrays.stream(s.split(&quot;\\\\&quot;)))
                .map(s -&gt; 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(&quot;C:\\formatted.txt&quot;),
            Files.lines(Paths.get(&quot;C:\\new.txt&quot;))
                .flatMap(s -&gt; Arrays.stream(s.split(&quot;\\\\&quot;)))
                .map(s -&gt; 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.

答案5

得分: 0

这是我会做的方式:

public class 读取文件{
    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)) { //如果可以,始终使用 try-with-resources
            while (read.hasNextLine()) {
                al.add(read.nextLine()); //读取并添加到 ArrayList(因此输入文件中可能有多行)
            }

            for (String str : al) {
                write.write(str.replace("\\", "\n")); //将所有反斜杠替换为换行符
                write.write('\n');
            }

            write.flush(); //在最后刷新 Writer,以便将所有内容写入文件
        } catch (FileNotFoundException e) {
            throw new RuntimeException("文件未找到。"); //不要吞掉异常,至少抛出 RuntimeException
        } catch (IOException ex) {
            throw new RuntimeException("IO 异常发生"); //不要吞掉异常,至少抛出 RuntimeException
        }
    }
}
英文:

This is how I would do it:

public class ReadingFile{
    public static void main(String[] args) {
        File in = new File(&quot;C:\\old.txt&quot;);
        File out = new File(&quot;C:\\new.txt&quot;);
        ArrayList&lt;String&gt; al = new ArrayList&lt;&gt;();

        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(&quot;\\&quot;, &quot;\n&quot;)); //replace all backslashes with newlines
                write.write(&#39;\n&#39;);
            }

            write.flush(); //flush the Writer at the end, so everything gets written to the file
        } catch (FileNotFoundException e) {
            throw new RuntimeException(&quot;File not found.&quot;); //Don&#39;t swallow exceptions, at least throw a RuntimeException
        } catch (IOException ex) {
            throw new RuntimeException(&quot;IO exception occured&quot;); //Don&#39;t swallow exceptions, at least throw a RuntimeException
        }
    }
}

huangapple
  • 本文由 发表于 2020年5月30日 00:30:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/62090566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定