Koray Tugay
Koray Tugay

Reputation: 23780

How should I represent a File in memory temporarily in Java?

So what I want to do is something like this: Assume I have a File object that is linked to a physical file in the system. I want to modify it a few times before writing the content back to a new file. How can I do this? So here is the sample code:

File x = new File("somefile.txt");
// Ask user to enter a String
Scanner s = new Scanner(x);
while(s.hasNextLine())
    String nextLine = s.nextLine();
    if(userString.equals(nextLine))
        nextLine = nextLine.toUpperCase();

Now at this point, I do not want to modify the file x itself. I also do not want to write a physical file. I just want a representation of the same file, in same order, but some lines in uppercase, so I can loop through the same lines again.

What I want do is I want to to be able to loop through the same (but modified) file again.

How can I do this?

Upvotes: 0

Views: 786

Answers (3)

cyrilantony
cyrilantony

Reputation: 294

You can use StringWriter to store the filecontent and convert to inputstream when required.

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Scanner;

public class FileRead {
    public static void main(String[] args) throws Exception {
        File x = new File("input.txt");
        StringWriter sWriter = readToStringWriter(x);
        InputStream fis = new ByteArrayInputStream(sWriter.toString()
                .getBytes());
        String filecontent = convertStreamToString(fis);
        System.out.println("File Content:\n" + filecontent);
    }

    static StringWriter readToStringWriter(File x) throws FileNotFoundException {
        StringWriter sWriter = new StringWriter();
        Scanner s = new Scanner(x);
        while (s.hasNextLine()) {
            String nextLine = s.nextLine();
            sWriter.write(nextLine);
            if (s.hasNextLine())
                sWriter.write(System.getProperty("line.separator"));
        }
        return sWriter;
    }

    static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }
}

Upvotes: 0

Duncan Jones
Duncan Jones

Reputation: 69339

Use Files.readAllLines() to consume the file into memory, as a list of strings. Make as many changes as you want before writing those back out to the file, using Files.write():

Path path = Paths.get("somefile.txt");

// Ask user to enter a String

List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext(); ) {
  String line = iterator.next();
  if (userString.equals(line)) {
    iterator.set(line.toUpperCase());
  }
}

Files.write(path, lines, StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING);

If you need to access this data as an input stream, as a comment on another answer suggests, you can adopt one of the suggestions from Java: accessing a List of Strings as an InputStream.

Upvotes: 1

jas
jas

Reputation: 10865

You could store each line in an ArrayList<String> as you read them in, and then iterate through the list as many times as you like before writing out the contents.

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

public class Fm {
    public static void main(String[] args) throws Exception {
        File x = new File("somefile.txt");
        ArrayList<String> fileLines = new ArrayList<String>();
        String userString = "bar";

        Scanner s = new Scanner(x);
        while(s.hasNextLine()) {
            String nextLine = s.nextLine();
            if(userString.equals(nextLine))
                nextLine = nextLine.toUpperCase();
            fileLines.add(nextLine);
        }

        for (String line : fileLines) {
            System.out.println("Do something with: " + line);
        }
    }
}


$ cat somefile.txt
foo
bar
baz


$ java Fm
Do something with: foo
Do something with: BAR
Do something with: baz

Upvotes: 1

Related Questions