我需要将文件对象传递给构造函数,并且需要在方法中构造一个构造函数。

我对为什么我的代码无法编译感到非常困惑。它给了我几个错误,我仍然在为第一个问题苦苦挣扎:sc无法解决。

这是我的课:

public class Reverser {
    public Reverser(File file) throws FileNotFoundException, IOException {
        Scanner sc = new Scanner(file);
    }
    public void reverseLines(File outpr) {
        PrintWriter pw = new PrintWriter(outpr);
        while (sc.hasNextLine()) {
            String sentence = sc.nextLine();
            String[] words = sentence.split(" ");
            new ArrayList < String > (Arrays.asList(words));
            Collections.reverse(wordsarraylist);
            if (wordsarraylist != null) {
                String listString = wordsarraylist.toString;
                listString = listString.subString(1, listString.length() - 1);
            }
        }
        pw.write(listString);
    }
}


这是我的主要:

import java.util.*;
import java.io.*;
public class ReverserMain {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        Reverser r = new Reverser(new File("test.txt"));
    }
}

最佳答案

您是否要向此类添加更多功能?您可以使用以下方法使其简单:

public static void reverseLines(File inputFile, File outPutFile) {
    try (Scanner sc = new Scanner(inputFile); PrintWriter pw = new PrintWriter(outPutFile)) {
        while (sc.hasNextLine()) {
            // your logic goes in here

        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}



您可以对资源使用try-catch块,将自动关闭流。
在写入输出文件时,如果该文件已经存在,是否要追加数据或擦除文件内容并写入一个全新的文件?

如果必须使用构造函数:

public class Reverser {

File inputFile;
File outputFile;

public Reverser(File inputFile, File outputFile) {
    this.inputFile = inputFile;
    this.outputFile = outputFile;
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

}

public void reverseLines() {
    try (Scanner sc = new Scanner(inputFile); PrintWriter pw = new PrintWriter(outputFile)) {
        while (sc.hasNextLine()) {
            // your logic goes in here

        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}


}

10-08 13:39
查看更多