简体   繁体   English

在文件IO中保留换行符和间距

[英]Preserving line breaks and spacing in file IO

I am workig on a pretty neat problem challenge that involves reading words from a .txt file. 我正在研究一个非常整洁的问题挑战,涉及从.txt文件中读取单词。 The program must allow for ANY .txt file to be read, ergo the program cannot predict what words it will be dealing with. 该程序必须允许读取任何.txt文件,因此,该程序无法预测将要处理的单词。

Then, it takes the words and makes them their "Pig Latin" counterpart, and writes them into a new file. 然后,它使用这些单词并使它们成为“ Pig Latin”的对应词,并将它们写入新文件。 There are a lot more requirements to this problem but siffice to say, I have every part solved save one...when printng to the new file I am unable to perserve the line spacing. 这个问题有更多的要求,但是很容易地说,我已经解决了每个部分的问题……当打印到新文件时,我无法保留行距。 That is to say, if line 1 has 5 words and then there is a break and line 2 has 3 words and a break...the same must be true for the new file. 也就是说,如果第1行有5个单词,然后有一个分隔符,而第2行有3个单词,并且有一个分隔符...对于新文件也必须如此。 As it stands now, it all works but all the converted words are all listed one after the other. 从目前的情况来看,这一切正常,但是所有转换后的单词都一个接一个列出。

I am interested in learning this so I am OK if you all wish to play coy in your answers. 我有兴趣学习这项知识,所以如果大家都希望在回答中扮演co弱的角色,我可以。 Although I have been at this for 9 hours so "semi-coy" will be appreaciated as well :) Please pay close attention to the "while" statements in the code that is where the file IO action is happening. 尽管我已经呆了9个小时,所以“半s”也会变得很::请密切注意发生文件IO操作的代码中的“ while”语句。 I am wondering if I need to utilize the nextLine() commands from the scanner and then make a string off that...then make substrings off the nextLine() string to convert the words one at a time. 我想知道是否需要利用扫描器中的nextLine()命令,然后从该字符串中提取一个字符串,然后从nextLine()字符串中获取子字符串,以一次转换一个单词。 The substrings could be splits or tokens, or something else - I am unclear on this part and token attempts are giving me compiler arrors exceptions "java.util.NoSuchElementException" - I do not seem to understand the correct call for a split command. 子字符串可能是拆分的或令牌的,或者是其他东西-在这一部分我不清楚,令牌的尝试给了我编译器错误例外“ java.util.NoSuchElementException”-我似乎不明白对split命令的正确调用。 I tried something like String a = scan.nextLine() where "scan" is my scanner var. 我尝试了类似String a = scan.nextLine()的方法,其中“ scan”是我的扫描仪变量。 Then tried String b = a.split() no go. 然后尝试String b = a.split()不行。 Anyway here is my code and see if you can figure out what I am missing. 无论如何,这是我的代码,看看您是否能找出我所缺少的内容。

Here is code and thank you very much in advance Java gods.... 这是代码,非常感谢Java诸神。

import java.util.*;
import javax.swing.*;
import java.io.*;
import java.text.*;

public class PigLatinTranslator
{
    static final String ay = "ay"; // "ay" is added to the end of every word in pig latin

    public static void main(String [] args) throws IOException
    {
        File nonPiggedFile = new File(...);
        String nonPiggedFileName = nonPiggedFile.getName();
        Scanner scan = new Scanner(nonPiggedFile);  

        nonPiggedFileName = ...;

        File pigLatinFile = new File(nonPiggedFileName + "-pigLatin.txt"); //references a file that may or may not exist yet

        pigLatinFile.createNewFile();
        FileWriter newPigLatinFile = new FileWriter(nonPiggedFileName + "-pigLatin.txt", true);
        PrintWriter PrintToPLF = new PrintWriter(newPigLatinFile);

        while (scan.hasNext()) 
        {
            boolean next;
            while (next = scan.hasNext()) 
            {
                 String nonPig = scan.next();
                 nonPig = nonPig.toLowerCase();
                 StringBuilder PigLatWord = new StringBuilder(nonPig);
                 PigLatWord.insert(nonPig.length(), nonPig.charAt(0) );
                 PigLatWord.insert(nonPig.length() + 1, ay);
                 PigLatWord.deleteCharAt(0);
                 String plw = PigLatWord.toString();

                 if (plw.contains("!") )
                 {
                     plw = plw.replace("!", "") + "!";
                 }

                 if (plw.contains(".") )
                 {
                     plw = plw.replace(".", "") + ".";
                 }

                 if (plw.contains("?") )
                 { 
                     plw = plw.replace("?", "") + "?"; 
                 }

                 PrintToPLF.print(plw + " ");
            }

            PrintToPLF.close();
        }
    }
}

Use BufferedReader , not Scanner . 使用BufferedReader而不是Scanner http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html

I leave that part of it as an exercise for the original poster, it's easy once you know the right class to use! 我将其的一部分留作原始海报的练习,一旦您知道使用正确的课程,这很容易! (And hopefully you learn something instead of copy-pasting my code). (希望您能学到一些东西,而不是复制粘贴我的代码)。

Then pass the entire line into functions like this: (note this does not correctly handle quotes as it puts all non-apostrophe punctuation at the end of the word). 然后将整行传递给这样的函数:(请注意,这不能正确处理引号,因为它会将所有非撇号标点放在单词的末尾)。 Also it assumes that punctuation is supposed to go at the end of the word. 它还假定标点应该在单词的末尾。

private static final String vowels = "AEIOUaeiou";
private static final String punct = ".,!?";

public static String pigifyLine(String oneLine) {
   StringBuilder pigified = new StringBuilder();
   boolean first = true;
   for (String word : oneLine.split(" ")) {
       if (!first) pigified.append(" ");
       pigified.append(pigify(word));
       first = false;
   }
   return pigified.toString();
}

public static String pigify(String oneWord) {
    char[] chars = oneWord.toCharArray();
    StringBuilder consonants = new StringBuilder();
    StringBuilder newWord = new StringBuilder();
    StringBuilder punctuation = new StringBuilder();
    boolean consDone = false; // set to true when the first consonant group is done

    for (int i = 0; i < chars.length; i++) {
        // consonant
        if (vowels.indexOf(chars[i]) == -1) {
            // punctuation
            if (punct.indexOf(chars[i]) > -1) {
                punctuation.append(chars[i]);
                consDone = true;
            } else {
                if (!consDone) { // we haven't found the consonants
                    consonants.append(chars[i]);
                } else {
                    newWord.append(chars[i]);
                }
            }
        } else {
            consDone = true;
            // vowel
            newWord.append(chars[i]);
        }
    }

    if (consonants.length() == 0) {
        // vowel words are "about" -> "aboutway"
        consonants.append("w");
    } 
    consonants.append("ay");

    return newWord.append(consonants).append(punctuation).toString();
}

You could try to store the count of words per line in a separate data structure, and use that as a guide for when to move on to the next line when writing the file. 您可以尝试将每行的单词数存储在单独的数据结构中,并以此为指导在编写文件时何时移至下一行。

I purposely made this semi-vague for you, but can elaborate on request. 我特意为您制作了这个模糊的图片,但可以根据要求进行详细说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM