找到你要的答案

Q:Why is there an extra line in the file I am writing?

Q:为什么我写的文件里有多余的一行?

How can i read all name of username from text file and write it into new text file. There are no compilation errors, but my output is incorrect. Help me find out the problem or give me a example. Thank you.

The file resident.txt:

  james|123
  kelvin|123

Expected result:

 fee.txt
 jan|james
 jan|kelvin

My end result:

 fee.txt
 jan|james
 jan|kelvin
 jan|

The source:

private void btnConfirmActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
    boolean flag = false;
    File file = new File("resident.txt");
    ArrayList al = FileFunction.getContent(file);
    for (Object obj : al) {
        String newobj = obj.toString();
        String s[] = newobj.split("\\|");

        String strMonth = txtMonth.getSelectedItem().toString();
        try (PrintWriter out = new PrintWriter(new FileWriter("fee.txt", true))) {
            out.println(strMonth + "|" + s[0]);
            flag = true;
            new ClerkPage(txtUsername.getText()).setVisible(true);
            this.dispose(); 
        } catch (Exception e) {
        } 
    }
    if(flag){
        JOptionPane.showMessageDialog(this, "Monthly fee was successfully charged! ");
    }
}    

FileFunction.java

package data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class FileFunction {

    public static ArrayList getContent(File f) {
        ArrayList ls = null;
        try (BufferedReader in = new BufferedReader(new FileReader(f));) {
            String line;
            ls = new ArrayList();
            while ((line = in.readLine()) != null) {
                ls.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ls;
    }

    public static boolean setContent(String oldInput, String newInput, File f) {
        boolean isDone = false;
        //temp bag
        ArrayList tempLs = null;
        try (Scanner scan = new Scanner(f);) {
            tempLs = new ArrayList();
            while (scan.hasNextLine()) {
                String tempLine = scan.nextLine();
                //check if it s the same with old..
                if (tempLine.equals(oldInput)) {
                    tempLs.add(newInput);                    
                } else {
                    tempLs.add(tempLine);
                }
            }
            if (makeNewContent(tempLs, f)) {
                isDone = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isDone;
    }

    private static boolean makeNewContent(ArrayList newContent, File f) {

        try {
            f.createNewFile();
            StringBuilder sb = new StringBuilder();
            for (Object object : newContent) {
                sb.append(object);
                sb.append("\r\n");
            }
            addContent(sb.toString(), f, false);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    public static boolean addContent(String input, File f, boolean append) {
        boolean isDone = false;
        try (PrintWriter out = new PrintWriter(new FileWriter(f, append))) {
            out.print(input);
            isDone = true;
        } catch (Exception e) {
        }
        return isDone;
    }

    public static boolean removeContent(String oldInput, File f) {
        boolean isDone = false;
        ArrayList tempLs = null;
        try (BufferedReader in = new BufferedReader(new FileReader(f))) {
            tempLs = new ArrayList();
            String line;
            while ((line = in.readLine()) != null) {
                if (line.equals(oldInput)) {
                    continue;
                }
                tempLs.add(line);
            }
            if (f.exists()) {
                f.delete();
            }
            if (makeNewContent(tempLs, f)) {
                isDone = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isDone;
    }
}

如何从文本文件中读取所有用户名,并将其写入新的文本文件中。没有编译错误,但输出错误。帮我找出问题或给我举个例子。谢谢您.

文件resident.txt:

  james|123
  kelvin|123

预期的结果:

 fee.txt
 jan|james
 jan|kelvin

我的归宿:

 fee.txt
 jan|james
 jan|kelvin
 jan|

源:

private void btnConfirmActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
    boolean flag = false;
    File file = new File("resident.txt");
    ArrayList al = FileFunction.getContent(file);
    for (Object obj : al) {
        String newobj = obj.toString();
        String s[] = newobj.split("\\|");

        String strMonth = txtMonth.getSelectedItem().toString();
        try (PrintWriter out = new PrintWriter(new FileWriter("fee.txt", true))) {
            out.println(strMonth + "|" + s[0]);
            flag = true;
            new ClerkPage(txtUsername.getText()).setVisible(true);
            this.dispose(); 
        } catch (Exception e) {
        } 
    }
    if(flag){
        JOptionPane.showMessageDialog(this, "Monthly fee was successfully charged! ");
    }
}    

filefunction.java

package data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class FileFunction {

    public static ArrayList getContent(File f) {
        ArrayList ls = null;
        try (BufferedReader in = new BufferedReader(new FileReader(f));) {
            String line;
            ls = new ArrayList();
            while ((line = in.readLine()) != null) {
                ls.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ls;
    }

    public static boolean setContent(String oldInput, String newInput, File f) {
        boolean isDone = false;
        //temp bag
        ArrayList tempLs = null;
        try (Scanner scan = new Scanner(f);) {
            tempLs = new ArrayList();
            while (scan.hasNextLine()) {
                String tempLine = scan.nextLine();
                //check if it s the same with old..
                if (tempLine.equals(oldInput)) {
                    tempLs.add(newInput);                    
                } else {
                    tempLs.add(tempLine);
                }
            }
            if (makeNewContent(tempLs, f)) {
                isDone = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isDone;
    }

    private static boolean makeNewContent(ArrayList newContent, File f) {

        try {
            f.createNewFile();
            StringBuilder sb = new StringBuilder();
            for (Object object : newContent) {
                sb.append(object);
                sb.append("\r\n");
            }
            addContent(sb.toString(), f, false);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    public static boolean addContent(String input, File f, boolean append) {
        boolean isDone = false;
        try (PrintWriter out = new PrintWriter(new FileWriter(f, append))) {
            out.print(input);
            isDone = true;
        } catch (Exception e) {
        }
        return isDone;
    }

    public static boolean removeContent(String oldInput, File f) {
        boolean isDone = false;
        ArrayList tempLs = null;
        try (BufferedReader in = new BufferedReader(new FileReader(f))) {
            tempLs = new ArrayList();
            String line;
            while ((line = in.readLine()) != null) {
                if (line.equals(oldInput)) {
                    continue;
                }
                tempLs.add(line);
            }
            if (f.exists()) {
                f.delete();
            }
            if (makeNewContent(tempLs, f)) {
                isDone = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isDone;
    }
}
answer1: 回答1:

There must be a newline at the end of resident.txt. I tried your code with a mock text file, and I reproduced your problem when I added an extra (blank) line at the bottom of resident.txt. You can get around this by adding this modification to FileFunction.getContent():

while ((line = in.readLine()) != null) {
    if (line.trim().length() > 0) {
        ls.add(line);
    }
}

As others have noted, you should change the way in which you are creating your ArrayLists :

ArrayList ls = null; // wrong
ArrayList<String> ls = null; // correct
ls = new ArrayList<String>(); // can do "new ArrayList<>();" if you're using Java 8

public static ArrayList getContent(File f) // wrong
public static ArrayList<String> getContent(File f) // correct

You get the idea. The space in between the < > brackets is where you put the type of object that will be stored in the array. Same goes for Map, Collection, etc.

必须有在resident.txt结束符。我想你的代码与一个模拟的文本文件,我复制你的问题时,我增加了一个额外的(空白)在resident.txt底线。您可以通过添加修改filefunction绕过这个。getcontent():

while ((line = in.readLine()) != null) {
    if (line.trim().length() > 0) {
        ls.add(line);
    }
}

正如其他人所指出的那样,你应该改变,你创造你的数组列表的方式:

ArrayList ls = null; // wrong
ArrayList<String> ls = null; // correct
ls = new ArrayList<String>(); // can do "new ArrayList<>();" if you're using Java 8

public static ArrayList getContent(File f) // wrong
public static ArrayList<String> getContent(File f) // correct

你得到的想法。空间之间的<;>;括号是你把对象的类型将被存储在数组里。同样适用于地图、收藏等。

java  file  arraylist