简体   繁体   English

Java:写入文件时产生太多换行符+异常错误?

[英]Java: Producing too many new lines character when writing to a file + Exception error?

Hey so I'm working on a personal project for myself and I'm having an issue. 嘿,所以我正在为自己做一个个人项目,但遇到了问题。 the following is a snippet of my code 以下是我的代码片段

while (inFile.hasNext()) {
            System.out.println("am i entering the loop");
            String aLine = inFile.nextLine();
            String[] aLineArray = aLine.split("\\s");
            String aName = aLineArray[0];
            String anIndex = aLineArray[1];
            System.out.println(anIndex);
            temp.println(aName + " " + anIndex + "\n");
        }

as you can see what I'm trying to do is split on the white space on each line of a text file, and write those 2 Strings with a space in between to another file.. Now this is what I've come to since it's actually producing something, which is an error 如您所见,我正在尝试在文本文件的每一行上的空白处进行拆分,然后将这两个字符串之间留有一个空格写入另一个文件中。它实际上正在产生某些东西,这是一个错误

am i entering the loop
4
am i entering the loop
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at pokemon.Pokedex.organizeByID(Pokedex.java:156)
at pokemon.Pokedex.main(Pokedex.java:12)

here's the snippet of code I was using before where I had issues with the "too many new lines" I've commented out the previous code to make it easier (assuming it will help) 这是我在遇到“太多新行”问题之前使用的代码段,我已经注释掉了先前的代码以使其变得更容易(假设它将有所帮助)

while (inFile.hasNext()) {
            System.out.println("am i entering the loop");
            String aLine = inFile.nextLine();
            /*String[] aLineArray = aLine.split("\\s");
            String aName = aLineArray[0];
            String anIndex = aLineArray[1];
            System.out.println(anIndex);
            temp.println(aName + " " + anIndex + "\n");*/
            temp.println(aLine);
        }

Any how the above produces a file, does exactly what it should be doing except instead of having a file like name index name index it's name index 以上内容产生文件的任何方式,都完全可以完成其应做的工作,除了拥有诸如名称索引,名称索引之类的文件而不是名称索引之外

name index Now I'm looking for a workaround to either a: remove that blank line (as that second snippet seems to be the most simplest way of going about this, b. resolve that error, as I have no idea what it means IndexOutOfBounds makes me assume that there aren't 2 words per line, but there is, I'll try to link to the file as well. c. Is there a way to open a file, read through it, reading all of it's contents along the way and then resetting the read pointer? Or to open a file and close and then reopen? Because it didn't work for me, I tried the inFile.hasNext() after opening, closing, and then reopening the file, and it didn't enter the while loop, because the condition was false, I assumed the pointer would be reset? 名称索引现在,我正在寻找以下一种解决方法:删除该空白行(因为第二个代码段似乎是解决此问题的最简单方法,b。解决该错误,因为我不知道它是什么意思IndexOutOfBounds让我假设每行没有2个单词,但是有一个,我也会尝试链接到文件c。有没有一种方法可以打开文件,通读文件,读取文件的所有内容方式然后重新设置读取指针?还是打开文件然后关闭然后重新打开?因为它对我不起作用,所以我在打开,关闭然后重新打开文件后尝试了inFile.hasNext()没有进入while循环,因为条件为假,我以为指针将被重置?

Here's the rest of my code if it helps 这是我其余的代码(如果有帮助的话)

public static void organizeByID(String file) throws IOException {
        //prints out a list of pokemon organized by ID based on file input
        File newFile = new File (file);
        Scanner inFile = new Scanner(newFile);

        ArrayList<String> lines = new ArrayList<String>();
        ArrayList<String> organized = new ArrayList<String>();
        PrintWriter temp = new PrintWriter("temp.txt", "UTF-8");
        while (inFile.hasNext()) {
            System.out.println("am i entering the loop");
            String aLine = inFile.nextLine();
            /*String[] aLineArray = aLine.split("\\s");
            String aName = aLineArray[0];
            String anIndex = aLineArray[1];
            System.out.println(anIndex);
            temp.println(aName + " " + anIndex + "\n");*/
            temp.println(aLine);
        }

        System.out.println("Why am i not entering here");

        File openFile = new File ("temp.txt");
        Scanner line = new Scanner(openFile);
        int i = 0;
        ArrayList<Integer> newList = new ArrayList<Integer>();

        while (line.hasNext() == true) {
            System.out.println("test");

            String PokeName = line.nextLine();
            if (PokeName != "") {
                //pokeDic[] creates an array of strings out of a split between the name and type of the pokemon
                String pokeDic[] = PokeName.split(" ");

                //add the line to a file?
                //create a new object using pokeDic[0] and pokeDic[1] as arguments, which are name and type

                //String type = p.getType();
                String name = pokeDic[0];
                //System.out.println(name + " " + type);
                int pokeIndex = Integer.parseInt(pokeDic[1]);
                String index = String.valueOf(pokeIndex);
                //System.out.println("This is a list of pokemon from the file " + file + "organized by pokedex index.");
                //System.out.println(name + " " + ID);
                String fileInformation = name + " " + index;
                newList.add(pokeIndex);
                System.out.println(newList);
                if (newList.get(i) == pokeIndex) {
                    organized.add(fileInformation + '\n');

                }
                else if (newList.get(i) > pokeIndex) {
                    organized.add(i-1, fileInformation + "\n");
                }
                else if (newList.get(i) < pokeIndex) {
                    organized.add(i+1, fileInformation + "\n");

                }
                else {
                    System.out.println("wtf is going on.");
                }
                System.out.println(organized);
                i++;}
            else {
                    System.out.println("wrong");
                }





        }
        temp.close();
        Collections.sort(newList);


        System.out.println(organized);
        System.out.println(newList);






    }

Now I realize that there are probably ALOT of issues with my code but i'd like to get it running and working before cleaning it up. 现在,我意识到我的代码可能存在很多问题,但是我希望在清理代码之前先使其运行并运行。 I'm using Eclipse, JDK 1.8? 我正在使用Eclipse,JDK 1.8? My txt files are open , read, and written to with notepad. 我的txt文件可以通过记事本打开,读取和写入。 I have notepad++ not sure if it would help by switching to it? 我有notepad ++,不确定是否切换到它会有帮助吗? If you could try to explain some of the bigger concepts that you're suggesting please do, I'm currently taking Data Structures I and we're just doing a refresher on Java currently. 如果您可以尝试解释所建议的一些更重要的概念,那么我目前正在使用Data Structures I,而我们目前只是在Java上进行一些复习。 If there's any other information you need please do mention so. 如果您需要其他任何信息,请提及。

here's fire.txt https://drive.google.com/file/d/0ByEhymKkTbLkc1dtRE1GaWNXX0E/view?usp=sharing 这是fire.txt https://drive.google.com/file/d/0ByEhymKkTbLkc1dtRE1GaWNXX0E/view?usp=sharing

temp is a file that is created, so I'm not gonna link to that, the code will generate it. temp是一个已创建的文件,因此我不会链接到该文件,代码将生成它。 Thanks ahead of time. 提前谢谢。 If you need me to clarify anything in my code (I'll understand, my code isn't exactly very clear and concise) feel free to say something. 如果您需要我澄清代码中的任何内容(我会理解,我的代码不是非常清楚和简洁),请随便说些什么。

trying System.lineSeparator 尝试System.lineSeparator

while (inFile.hasNext()) {
            System.out.println("am i entering the loop");
            String aLine = inFile.nextLine();
            /*String[] aLineArray = aLine.split("\\s");
            String aName = aLineArray[0];
            String anIndex = aLineArray[1];
            System.out.println(anIndex);
            temp.println(aName + " " + anIndex + "\n");*/
            temp.print(aLine);
            temp.print(System.lineSeparator());
        }

yields the same thing 产生相同的东西

ie Charmander 4 即Charmander 4

Charmeleon 5 变色龙5

The println() method adds a new line. println()方法添加新行。 Try the print() method instead. 请尝试使用print()方法。


You can then manually control any newlines you need using: 然后,您可以使用以下方法手动控制所需的任何换行符:

print(String.format("%n"));
print(System.getProperty("line.separator"));
print(System.lineSeparator()); // Java 7+

See How do I get a platform-dependent new line character? 请参阅如何获得与平台有关的换行符?

Exception is because of "negative" split, elemnt[1] is absent. 异常是由于“负数”拆分,elemnt [1]不存在。 (You show only part of code, I guess) (我猜您只显示部分代码)

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

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