java cannot create file by 3 methods

流过昼夜 提交于 2019-12-24 16:12:06

问题


I have a test.txt in my active directory.I need to create three methods:

  1. First one has to create an output file and reverse the order of the lines.
  2. Second the order of the words
  3. The third the order of the lines and the words. test.txt contains the input.

I developed every method to work on its own but somehow when I call all three at the same time it doesnt seem to work. What am i doing wrong? This is my main:

 import java.io.*;
  public class DemoReverser {
  public static void main (String [] args)
     throws IOException, FileNotFoundException {
     Reverser r = new Reverser(new File("test.txt"));
     r.completeReverse(new File("out3.txt"));
     r.reverseEachLine(new File("out2.txt"));
     r.reverseLines(new File("out1.txt"));
 } }

and this is my class.

import java.util.*;
import java.io.*; 

public class Reverser {

Scanner sc = null ;
Scanner sc2 = null;

//constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file)throws FileNotFoundException, IOException{

 sc = new Scanner (file); 
}

//this method reverses the order of the lines in the output
//prints to output file specified in argument.
public void reverseLines(File outpr)throws FileNotFoundException, IOException{

    List<String> wordsarraylist = new ArrayList<String>();

    while(sc.hasNextLine()){
        wordsarraylist.add(sc.nextLine());
        }

    Collections.reverse(wordsarraylist);

    FileWriter writer = new FileWriter(outpr,true); 

    for(String str: wordsarraylist) {
        writer.write(str+System.lineSeparator());
        }
    writer.flush();
    writer.close();
}




//this method reverses the order of the words in each line of the input
//and prints it to output file specified in argument.
public void reverseEachLine(File outpr)throws FileNotFoundException, IOException{

    while(sc.hasNextLine()){
        String sentence = sc.nextLine();
        String[] words = sentence.split(" ");
        ArrayList<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
        Collections.reverse(wordsarraylist);
        FileWriter writer = new FileWriter(outpr,true); 

        for(String str: wordsarraylist) {
            writer.write(str + " ");
            }

        writer.write(System.lineSeparator());
        writer.flush();
        writer.close();
    }
 }

//this methhod reverses the order of the words in each sentence of the input
//then writes it to output file specified in argument
//then uses the output file as input and reverses the order of the sentences
//then overwrites the ouput file with the result
//the output file will contain the input sentences with their words reversed
// and the order of sentences reversed.
public void completeReverse(File outpr)  throws FileNotFoundException, IOException{

 while(sc.hasNextLine()){
        String sentence = sc.nextLine();
        String[] words = sentence.split(" ");
        ArrayList<String> wordsarraylist2 = new ArrayList<String>(Arrays.asList(words));
        Collections.reverse(wordsarraylist2);
        FileWriter writer = new FileWriter(outpr,true); 

        for(String str: wordsarraylist2) {
            writer.write(str + " ");
         }
         writer.write(System.lineSeparator());  
         writer.flush();
         writer.close();
    }

    sc2 = new Scanner (outpr);

    List<String> wordsarraylist = new ArrayList<String>();

    while(sc2.hasNextLine()){
        wordsarraylist.add(sc2.nextLine());
    }

    Collections.reverse(wordsarraylist);

    PrintWriter erase = new PrintWriter(outpr);
    erase.print("");
   // erase.flush();
    erase.close();

    FileWriter writer = new FileWriter(outpr,true); 

    for(String str: wordsarraylist) {
        writer.write(str+System.lineSeparator());
    }
    writer.flush();
    writer.close();





}

}

When I run the program, out1 file gests created, which is the output file for my first method but it is empty. I don't get out2 file created by second method and out3 is fine. What am I doing wrong? What is missed


回答1:


Add writer.flush(); before writer.close(); in all three methods

And other thing - Scanner is initialized with File only once in constructor. It has to be re-initialized in other methods.

sc = new Scanner (file); // the scanner should be available in all three methods

For catching exceptions, use

try{
   // your code
}catch(Exception err){
   err.printStackTrace();
} 

After running your code, output3.txt is generated (First method call). Later Scanner is not available since end of the file has been reached.

Fix : Scanner should be re-initialized for next two methods.

EDIT: ( Updating answer with your chat feedback)

1) Create three scanners sc1,sc2 and sc3 due to your limitations. I would suggest to re-initialize the scanner in every method with the file being worked upon.

2) String reversal in easier way without using StringBuffer reverse() API ( For learning purpose)

int length = str.length();
  String reverse = "";
  for ( int i = length - 1 ; i >= 0 ; i-- ){
     reverse = reverse + str.charAt(i);
  }



回答2:


It's possible if you haven't write permission where you currently trying. So you get an error when testing.

However you have made some few mistakes in code. reverseEachLine method was not worked and you should not waste code to create completeReverse method. Please note following things.

  • Construct the Scanner when you need it
  • Remember to close the Scanner
  • Write processed file after closing the Scanner
  • Remove append if not necessary in Filewriter
  • Remember to flush FileWriter
  • Identify similarities and relationships between methods (complete reverse is a combination of line reverse and word reverse)

public class MyReverser {

private File inputFile;

public MyReverser(File file) {
    this.inputFile = file;
}

public void reverseLines(File outpr) throws FileNotFoundException, IOException {
    Scanner sc = new java.util.Scanner(inputFile);
    List<String> wordsarraylist = new ArrayList<String>();
    while (sc.hasNextLine()) {
        wordsarraylist.add(sc.nextLine());
    }
    sc.close();

    Collections.reverse(wordsarraylist);

    FileWriter writer = new FileWriter(outpr, false);
    for (String str : wordsarraylist) {
        writer.write(str + System.lineSeparator());
    }
    writer.flush();
    writer.close();
}

public void reverseEachLine(File outpr) throws FileNotFoundException, IOException {
    Scanner sc = new Scanner(inputFile);

    ArrayList<List<String>> wordsarraylist = new ArrayList<List<String>>();
    while (sc.hasNextLine()) {
        String sentence = sc.nextLine();

        List words = Arrays.asList(sentence.split(" "));
        Collections.reverse(words);
        wordsarraylist.add(words);
    }

    FileWriter writer = new FileWriter(outpr, false);
    for (List<String> list : wordsarraylist) {
        for (String string : list) {
            writer.append(string + " ");
        }
        writer.append(System.lineSeparator());
    }
    writer.flush();
    writer.close();
}

public void completeReverse(File outpr) throws FileNotFoundException, IOException {
    //reverse lines first
    reverseLines(outpr);

    //then reverse words
    reverseEachLine(outpr);
}

}




回答3:


The scenario here was the scanners were instance variables and once read in one of your operations method, it won't have more to read when you call the next method from Demo class. Have made the changes to read the sentences and store it in the instance, so that it can be reused in each method.

import java.util.*;
import java.io.*;

public class Reverser {

    Scanner sc = null;
    Scanner sc2 = null;

    boolean hasReadFile;
    List<String> fileLinesList;

    // constructor takes input file and initialize scanner sc pointing at input
    public Reverser(File file) throws FileNotFoundException, IOException {

        sc = new Scanner(file);
        hasReadFile = false;
        fileLinesList = new ArrayList<>();
    }

    // this method reverses the order of the lines in the output
    // prints to output file specified in argument.
    public void reverseLines(File outpr) throws FileNotFoundException,
            IOException {

        List<String> wordsarraylist = new ArrayList<String>();
        readFile();
        for (String sentence : fileLinesList) {
            wordsarraylist.add(sentence);
        }

        Collections.reverse(wordsarraylist);

        FileWriter writer = new FileWriter(outpr, true);

        for (String str : wordsarraylist) {
            writer.write(str + System.lineSeparator());
        }
        writer.flush();
        writer.close();
    }

    // this method reverses the order of the words in each line of the input
    // and prints it to output file specified in argument.
    public void reverseEachLine(File outpr) throws FileNotFoundException,
            IOException {
        readFile();
        for (String sentence : fileLinesList) {
            String[] words = sentence.split(" ");
            ArrayList<String> wordsarraylist = new ArrayList<String>(
                    Arrays.asList(words));
            Collections.reverse(wordsarraylist);
            FileWriter writer = new FileWriter(outpr, true);

            for (String str : wordsarraylist) {
                writer.write(str + " ");
            }

            writer.write(System.lineSeparator());
            writer.flush();
            writer.close();
        }
    }

    private void readFile() {
        if (!hasReadFile) {
            while (sc.hasNextLine()) {
                fileLinesList.add(sc.nextLine());
            }
            fileLinesList = Collections.unmodifiableList(fileLinesList);
            hasReadFile = true;
        }
    }

    // this methhod reverses the order of the words in each sentence of the
    // input
    // then writes it to output file specified in argument
    // then uses the output file as input and reverses the order of the
    // sentences
    // then overwrites the ouput file with the result
    // the output file will contain the input sentences with their words
    // reversed
    // and the order of sentences reversed.
    public void completeReverse(File outpr) throws FileNotFoundException,
            IOException {
        readFile();
        for (String sentence : fileLinesList) {
            String[] words = sentence.split(" ");
            ArrayList<String> wordsarraylist2 = new ArrayList<String>(
                    Arrays.asList(words));
            Collections.reverse(wordsarraylist2);
            FileWriter writer = new FileWriter(outpr, true);

            for (String str : wordsarraylist2) {
                writer.write(str + " ");
            }
            writer.write(System.lineSeparator());
            writer.flush();
            writer.close();
        }

        sc2 = new Scanner(outpr);

        List<String> wordsarraylist = new ArrayList<String>();

        while (sc2.hasNextLine()) {
            wordsarraylist.add(sc2.nextLine());
        }

        Collections.reverse(wordsarraylist);

        PrintWriter erase = new PrintWriter(outpr);
        erase.print("");
        // erase.flush();
        erase.close();

        FileWriter writer = new FileWriter(outpr, true);

        for (String str : wordsarraylist) {
            writer.write(str + System.lineSeparator());
        }
        writer.flush();
        writer.close();

    }
}


来源:https://stackoverflow.com/questions/32752820/java-cannot-create-file-by-3-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!