質問

Im trying to write a method that updates a .txt file with a new String.....what ive done is have it 1) read all the strings from the previously made txt file 2)puts them into an arraylist 3) writes a new string to the arraylist 4) then writes the toString() objects of that arraylist to a new file

it only writes the newest string to the file and none of the others even if i edit the file with multiple lines

here is what i have:

public static void updateNames(String newName) throws FileNotFoundException {
        name = new File("names.txt");
        infile = new Scanner(name);
        ArrayList<String> nameslist = new ArrayList<>();
        while(infile.hasNext()) {
            nameslist.add(infile.nextLine());
        }
        infile.close();
        nameslist.add(newName);
        names = new PrintWriter("names.txt");
        for(int i=0;i<nameslist.size();i++) {
            names.println(nameslist.get(i).toString());
        }
        names.close();
        System.out.println("else");
    }

just to be as clear as i can {name, names, and infile} are all declared as static void at the beginning of the class

thanks in advance for any help

役に立ちましたか?

解決

use infile.hasNextLine() instead of infile.hasNext()

change

   while(infile.hasNext())

to

  while(infile.hasNextLine())

and small correction

change

 names.println(nameslist.get(i).toString());

to

 names.println(nameslist.get(i)); //nameslist holds String objects no need to convert to String again.

if not solved the issue add countline variable and make sure how many lines you read from the file.

 int countline;
 while(infile.hasNext()) {
     nameslist.add(infile.nextLine());
     countline++;        
 }     
 System.out.println("Number of line: "+ countline);

他のヒント

Why dont you try this :

public static void updateNames(String newName) throws FileNotFoundException   {
    try {
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
        out.println(newName);
        out.close();
    } catch (IOException e) {
}

It will append newName at the end of the file text.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top