Java 版画作家用空格换行

Java 版画作家用空格换行,java,printwriter,Java,Printwriter,我有一个读取器读取一个文件来编辑它,然后用printwriter保存它。 开始输入如下 问题是,有时空格会被误认为是新行。在第一次之后,我更进一步地再次切割它 像 我尝试了一些不同的拆分字符,比如(它实际上是什么(你可以在System.out.println中看到)),但我无法让它正常工作 原始加载的文本文件为,getText的输出为 if(上次单击!=0){ 字符串路径; 开关(上次单击){ 案例1: path=“data/alyxia\u status.got”; 打破 案例2: path=

我有一个读取器读取一个文件来编辑它,然后用printwriter保存它。 开始输入如下 问题是,有时空格会被误认为是新行。在第一次之后,我更进一步地再次切割它 像

我尝试了一些不同的拆分字符,比如
(它实际上是什么(你可以在System.out.println中看到)),但我无法让它正常工作

原始加载的文本文件为,getText的输出为

if(上次单击!=0){
字符串路径;
开关(上次单击){
案例1:
path=“data/alyxia\u status.got”;
打破
案例2:
path=“data/mog\u status.got”;
打破
案例3:
path=“data/telias\u status.get”;
打破
违约:
path=“data/tiernen\u status.got”;
}
String text=textPane.getText();
字符串toWrite=text.substring(44,text.length()-16);
系统输出打印项次(toWrite);
String[]parts=toWrite.split(“
”); 文件编写器文件编写器; 试一试{ fileWriter=新的fileWriter(路径); PrintWriter PrintWriter=新的PrintWriter(fileWriter); printWriter.print(部分[0]);
对于(int i=1;i以下代码对我来说运行良好,请尝试调用
printToFile
方法,并将
String
数组作为参数传递给is。通过在单独的方法中隔离有问题的代码,应该更容易调试。我还注意到您正在将
String
对象与运算符进行比较,这不是ad被钳制,不做你认为它能做的事。阅读此获取更多信息

public static void printToFile(String path, String[] output) {

    FileWriter fileWriter;
    try {
        fileWriter = new FileWriter(path);
        PrintWriter printWriter = new PrintWriter(fileWriter);
        printWriter.print(output[0]);
        for (int i = 1; i < output.length; i++)
        {
            /* DO NOT compare string with opeators like "!=" or "==,
             * instead use equals method to properly compare them
             */
            if (!output[i].equals("") && !output[i].equals(" ")) {
                printWriter.println();
                printWriter.print(output[i]);
            }
        }
        printWriter.close();
    }
    catch (java.io.IOException e1) {
        e1.printStackTrace();
        System.err.println("Saving failed");
    }
}

public static void main(String[] args) throws IOException
{
    Path path = Paths.get("sample.txt");
    String[] text = new String[] { "these ", " lines ", "should", " be  ", " in   new ", "line" };

    printToFile(path.toString(), text);
    Files.readAllLines(path).forEach(System.out::println);
}
编辑:评论中提到的@DodgyCodeException可能是问题的实际原因。为了可见性起见,我将粘贴评论:


由于您的text.substring(44,text.length()-16);,文本的前44个字符将被丢弃。这包括“-Base”(刚好在“损坏”之前)之前的所有字符

完整解决方案

我已在以下代码中为您的问题编写了完整的解决方案。请尝试该代码,看看它是否适合您,然后阅读代码下面的说明:

public class Main {

    /**
     * Use {@link StringBuilder} to build a single {@code String}
     * from the read contents of file located under given path.
     * 
     * @param path {@code Path} of the file to read
     * @throws IOException if an I/O error occurs reading from the file
     *         or a malformed or unmappable byte sequence is read.
     */
    private static String getInputFileContent(Path path) throws IOException {

        StringBuilder sb = new StringBuilder();
        Files.readAllLines(path).forEach(sb::append);
        return sb.toString();
    }

    /**
     * @return the matched content contained in <body> tag within
     *         the provided text or {@code null} if there was no match.
     */
    private static @Nullable String getHTMLBodyFromText(String text) {

        Pattern pattern = Pattern.compile("(?:\\s*?<body>)(?:\\s*)((.*\\s)*)</body>");
        Matcher matcher = pattern.matcher(text);
        return matcher.find() ? matcher.group(1) : null;
    }

    public static void printToFile(Path path, String output) {

        String toWrite = getHTMLBodyFromText(output);
        if (toWrite == null) {
            System.err.println("Unable to find body");
            return;
        }
        String[] parts = toWrite.split("<br>");
        FileWriter fileWriter;
        try {
            fileWriter = new FileWriter(path.toString());
            PrintWriter printWriter = new PrintWriter(fileWriter);
            printWriter.print(parts[0]);
            for (int i = 1; i < parts.length; i++)
            {
                /* DO NOT compare string with opeators like "!=" or "==,
                 * instead use equals method to properly compare them
                 */
                if (!parts[i].equals("") && !parts[i].equals(" ")) {
                    printWriter.println(parts[i]);
                    printWriter.print(parts[i]);
                }
            }
            printWriter.close();
        }
        catch (java.io.IOException e1) {
            e1.printStackTrace();
            System.err.println("Saving failed");
        }
    }
    public static void main(String[] args) throws IOException
    {
        Path inputPath = Paths.get("input.txt");
        Path outputPath = Paths.get("output.txt");

        printToFile(outputPath, getInputFileContent(inputPath));
    }
}
公共类主{
/**
*使用{@link StringBuilder}构建单个{@code String}
*从位于给定路径下的文件的读取内容。
* 
*要读取的文件的@param path{@code path}
*@在读取文件时发生I/O错误时引发IOException
*或者读取格式错误或不可映射的字节序列。
*/
私有静态字符串getInputFileContent(路径路径)引发IOException{
StringBuilder sb=新的StringBuilder();
Files.readAllLines(path).forEach(sb::append);
使某人返回字符串();
}
/**
*@返回内标签中包含的匹配内容
*提供的文本或{@code null}(如果不匹配)。
*/
私有静态@Nullable String getHTMLBodyFromText(字符串文本){
Pattern=Pattern.compile((?:\\s*?)(?:\\s*)((.*\\s)*”);
Matcher Matcher=pattern.Matcher(文本);
返回matcher.find()?matcher.group(1):null;
}
公共静态void打印文件(路径、字符串输出){
字符串toWrite=getHTMLBodyFromText(输出);
if(toWrite==null){
System.err.println(“找不到正文”);
返回;
}
String[]parts=toWrite.split(“
”); 文件编写器文件编写器; 试一试{ fileWriter=新的fileWriter(path.toString()); PrintWriter PrintWriter=新的PrintWriter(fileWriter); printWriter.print(部分[0]); 对于(int i=1;i
我已使用
Regex
查找您提供的输入文件的
标记中包含的文本(我们想要的实际内容位于
组1
),这是导致此问题的部分。如果您有兴趣了解此代码中包含的模式如何工作,请参阅此


代码的其余部分工作正常,因此只需调用
printToFile
方法并传递
textPane.getText()的返回值
作为
输出
字符串
参数,它将为您处理所需结果并打印到位于您选择的路径下的文本文件中。

也许换行符是原始数据的真实部分?当我第一次加载数据时,没有换行符,换行符在保存并重新加载后进入e由于您的
text.substring(44,text.length()-16);
,文本的前44个字符被丢弃。这包括“-Base”(刚好在
public class Main {

    /**
     * Use {@link StringBuilder} to build a single {@code String}
     * from the read contents of file located under given path.
     * 
     * @param path {@code Path} of the file to read
     * @throws IOException if an I/O error occurs reading from the file
     *         or a malformed or unmappable byte sequence is read.
     */
    private static String getInputFileContent(Path path) throws IOException {

        StringBuilder sb = new StringBuilder();
        Files.readAllLines(path).forEach(sb::append);
        return sb.toString();
    }

    /**
     * @return the matched content contained in <body> tag within
     *         the provided text or {@code null} if there was no match.
     */
    private static @Nullable String getHTMLBodyFromText(String text) {

        Pattern pattern = Pattern.compile("(?:\\s*?<body>)(?:\\s*)((.*\\s)*)</body>");
        Matcher matcher = pattern.matcher(text);
        return matcher.find() ? matcher.group(1) : null;
    }

    public static void printToFile(Path path, String output) {

        String toWrite = getHTMLBodyFromText(output);
        if (toWrite == null) {
            System.err.println("Unable to find body");
            return;
        }
        String[] parts = toWrite.split("<br>");
        FileWriter fileWriter;
        try {
            fileWriter = new FileWriter(path.toString());
            PrintWriter printWriter = new PrintWriter(fileWriter);
            printWriter.print(parts[0]);
            for (int i = 1; i < parts.length; i++)
            {
                /* DO NOT compare string with opeators like "!=" or "==,
                 * instead use equals method to properly compare them
                 */
                if (!parts[i].equals("") && !parts[i].equals(" ")) {
                    printWriter.println(parts[i]);
                    printWriter.print(parts[i]);
                }
            }
            printWriter.close();
        }
        catch (java.io.IOException e1) {
            e1.printStackTrace();
            System.err.println("Saving failed");
        }
    }
    public static void main(String[] args) throws IOException
    {
        Path inputPath = Paths.get("input.txt");
        Path outputPath = Paths.get("output.txt");

        printToFile(outputPath, getInputFileContent(inputPath));
    }
}