如何从文件中读取数字,字符串或字符。我发现了很多方法,但我不知道最佳和清晰的方法。我想进行诸如系统控制台之类的输入/输出操作。
我创建了2个文件input.in和output.out,我想从input.in读取一个数字并将其打印到output.out。
import java.util.Scanner;
import java.io.*;
public class MainClass {
public static void main(String[] args) throws IOException {
File file = new File("input.in");
Scanner scanner = new Scanner(file);
String a = scanner.nextLine();
System.out.println(a);
}
}
我首先要测试是否可以从文件中读取内容,但是我知道了:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at MainClass.main(MainClass.java:9)
在文件input.in中,我有:
文件
我/ o
答案 0 :(得分:1)
就像评论中提到的RealSkeptic一样,我怀疑您的应用程序找不到您提供的文件。我建议您采用以下代码:
import java.util.Scanner;
import java.io.*;
public class MainClass {
public static void main(String[] args) throws Exception {
String filePath = "c:\\absolute\\path\\to\\input.in";
File file = new File(filePath);
if(file.exists()) {
System.out.println("Reading contents of file at: " + filePath)
try (Scanner scanner = new Scanner(file)) {
while(scanner.hasNext()) {
String a = scanner.nextLine();
System.out.println(a);
}
}
}
else {
System.out.println("File not found at: " + filePath);
}
}
}
参考文献:
答案 1 :(得分:1)
您可以使用FileInputStream
和FileOutputStream
来做到这一点。
希望这会达到您的目的
import java.util.Scanner;
import java.io.*;
public class MainClass {
public static void main(String[] args) throws IOException {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream("IN File");
outputStream = new FileOutputStream("OUT File");
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
byte[] strToBytes = line.getBytes();
outputStream.write(strToBytes);
outputStream.write(System.getProperty("line.separator").getBytes());
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
}
}
答案 2 :(得分:0)
路径错误。对于那些也有我的问题的人,这里是输入/输出操作的代码:
import java.util.Scanner;
import java.io.*;
public class MainClass {
public static void main(String[] args) throws IOException {
//the root path is your project name
File in = new File("input.in");
File out = new File("output.out");
Scanner scannerInput = new Scanner(in);
BufferedWriter writer = new BufferedWriter(new FileWriter(out));
String string;
while(scannerInput.hasNextLine()) {
string = scannerInput.nextLine();
writer.write(string);
writer.newLine();
}
writer.flush();//very important
scannerInput.close();
writer.close();
}
}