我有一个包含 10 行的文件,每行都有一个数字。我想读取这些行,将数字乘以 2,然后将结果写入另一个文件。这是我的代码,但我不起作用。我的代码:
public class CopyFile {
public static void main(String[] args) throws IOException {
FileReader reader = null;
FileWriter writer = null;
try {
reader = new FileReader("kopiere.txt"); //read from this file
writer = new FileWriter("einfuegen.txt"); //write in this file
int c;
while ((c = reader.read()) != -1) {
int i = Integer.parseInt(String.valueOf(c)); //convert content of line into int
i = i*2; //multiply with 2
writer.write(i); //write the result into the file "einfuegen.txt"
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
if (reader != null) {
reader.close();
}
}
}
}
文件的文件内容应该是2,4,6,8,10...,但是却是
bdfhjlnprb`
最佳答案
writer.write(i)
将由所提供的 int
参数的低 16 位表示的字符写入流,而不是该整数的字符串表示形式。如果您想将该整数的字符串表示形式写入流,则需要首先转换为字符串表示形式。例如:
writer.write(Integer.toString(i));
关于java - 从文件中读取数字,乘以2,写入文件(JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48814595/