【问题标题】:java cannot create file by 3 methodsjava无法通过3种方法创建文件
【发布时间】:2015-09-24 03:26:40
【问题描述】:

我的活动目录中有一个 test.txt。我需要创建三个方法:

  1. 第一个必须创建一个输出文件并反转行的顺序。
  2. 单词的第二个顺序
  3. 第三行和单词的顺序。 test.txt 包含输入。

我开发了每种方法来独立工作,但不知何故,当我同时调用所有三个方法时,它似乎不起作用。 我究竟做错了什么? 这是我的主要内容:

 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"));
 } }

这是我的课。

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();





}

}

当我运行程序时,创建了 out1 文件,这是我第一个方法的输出文件,但它是空的。我没有得到由第二种方法创建的 out2 文件,而 out3 很好。 我究竟做错了什么?错过了什么

【问题讨论】:

  • 重新措辞,将点移到下一行以提高可读性。以及代码格式框。

标签: java output reverse


【解决方案1】:

在所有三种方法中在writer.close(); 之前添加writer.flush();

还有其他的——扫描器在构造函数中只用文件初始化一次。必须用其他方法重新初始化。

sc = 新扫描仪(文件); // 扫描器应该在所有三种方法中都可用

要捕获异常,请使用

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

运行代码后,将生成 output3.txt(第一个方法调用)。由于已到达文件末尾,因此稍后扫描仪不可用。

修复:扫描仪应该为接下来的两种方法重新初始化。

编辑:(使用您的聊天反馈更新答案)

1) 由于您的限制,创建三个扫描仪 sc1、sc2 和 sc3。我建议使用正在处理的文件在每种方法中重新初始化扫描仪。

2) 不使用 StringBuffer reverse() API 以更简单的方式反转字符串(用于学习目的)

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

【讨论】:

  • 你有什么异常吗?你能捕捉和打印异常吗?
  • 没有异常...你能告诉我如何捕捉和打印异常吗?
  • 我无法初始化扫描仪,因为文件只是构造函数的参数,我不能更改它。
  • 从你的程序中,我得到了 output3.txt 的倒序
  • 这很好,但我需要其他两种方法才能工作。还有一件事我应该为每种方法添加捕获异常代码吗?
【解决方案2】:

如果您没有在当前尝试的地方写权限,这是可能的。所以你在测试的时候会报错。

但是,您在代码中犯了一些错误。 reverseEachLine 方法无效,您不应浪费代码来创建 completeReverse 方法。请注意以下事项。

  • 在需要时构造Scanner
  • 记得关闭Scanner
  • 关闭Scanner后写入处理过的文件
  • Filewriter 中不需要的删除追加
  • 记得刷新FileWriter
  • 确定方法之间的相似性和关系(完全反向是行反向和单词反向的组合)

公共类 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】:

    这里的场景是扫描器是实例变量,一旦在您的一个操作方法中读取,当您从 Demo 类调用下一个方法时,它就不会再读取更多内容了。已进行更改以读取句子并将其存储在实例中,以便可以在每个方法中重复使用。

    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();
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      相关资源
      最近更新 更多