简体   繁体   中英

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?

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? My txt files are open , read, and written to with notepad. I have notepad++ not sure if it would help by switching to it? 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. 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

temp is a file that is created, so I'm not gonna link to that, the code will generate it. 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

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

Charmeleon 5

The println() method adds a new line. Try the print() method instead.


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. (You show only part of code, I guess)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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