[英]Can we call synchronized method of an object inside the constructor of the object in Java?
[英]JAVA Scanner object inside my constructor, cannot call it in my method
我需要将文件对象传递给构造函数,并且需要在方法中构造一个构造函数。
我对为什么我的代码无法编译感到非常困惑。 它给了我几个错误,而我仍然在努力解决第一个错误: 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();
}
}
}
在构造函数之外声明sc:
Scanner sc = null ;
public Reverser(File file)throws FileNotFoundException, IOException{
sc = new Scanner (file);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.