嗨我有这个代码打印每一行的最后一个单词,我想要的东西完全是这个代码所做的但是用第一个单词(不要嘲笑我,我不是程序员)
private static void readFile1(String in, String out) throws IOException
{
FileInputStream fis = new FileInputStream(new File(in));
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(out), "utf-8"));
String line = null;
while ((line = br.readLine()) != null)
{
if(line.length() > 0)
{
String[] words = line.split("\\s+");
//System.out.println(words[words.length - 1]);
writer.write(words[words.length - 1]);
writer.newLine();
}
}
br.close();
writer.close();
fis.close();
}
答案 0 :(得分:2)
而不是:
writer.write(words[words.length - 1]);
使用
writer.write(words[0]);//assuming you wont have empty line.
如果你可以有空行,那么尝试使用:
if (words.length != 0) {
writer.write(words[0]);
}
答案 1 :(得分:1)
替换:
writer.write(words[words.length - 1]);
with:
writer.write(words[0]);
干杯!
答案 2 :(得分:0)
替换:
writer.write(words[words.length - 1]);
使用:writer.write(words[0]);
或使用:
while((line = br.hasNextLine()))
{...
writer.write(words[0]);
...}