I have a method that reads from a file and puts all the information into an ArrayList. After that it can be read in a certain format using a method.
Now what I want know is: Is it possible to use Scanner and the PrintWriter class only, to copy the exact same output from the terminal to a new txt file?
Thanks
Is it possible to use Scanner and the PrintWriter class only, to copy the exact same output from the terminal to a new txt file?
Yes. It is possible. You can either:
1) Read directly from the original file (with Scanner) and write to a new file (with PrintWriter) or
2) If you want the output of your program to be saved in a text file:
C:\> java myProgram > myFile.txt
If you store your entire file data into a data structure like ArrayList first, there is a tendency that if the text file is too large, you will have a problem storing everything into the ArrayList at one go.
Related
user u1 Khulbe Sharma gupta
These are the entries in the CSV file i want to know if there is a Java inbuilt function that can directly give me the number of lines in CSV file? In this case, it would be 5 lines.
A built-in functionality would be to open the file and read how many lines there are. In Java8 for example, it would look like this:
final Path path = Paths.get(ClassLoader.getSystemResource("your.csv").toURI());
return Files.lines(path).skip(1L).count(); // skip(1L) to ignore the titles
CSV has nothing to do with it. All you need is a line count. This can be accomplished in two lines of code with a LineNumberReader:
lineNumberReader.skip(Long.MAX_VALUE);
int lines = lineNumberReader.getLineNumber();
Super CSV. Have a close look at Example CSV file and the output.
You can put a variable to keep count while using Super CSV to find the number of lines. Only thing you have to do is to add the jar to your classpath and then access its methods
I am generating random numbers and putting that in a file and from that file I m reading the values. Now while reading it is reading all the values which has been put to the file again rather than reading the last added value. So what I want is to delete the contents of the file before writing any random number to it again so that when it reads from it, it will only read the last added value.
If you're doing this all at the same time via RandomAccessFile, just call RandomAccessFile.setLength(0).
If you're doing it via a FileOutputStream or FileWriter, just create a new one without the append parameter, or with that parameter set to `false.
Write an empty string into the file like below
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
How can i prevent prinwriter in java from overwriting what's inside of that particular file?
Ex. I have a student.txt file. I already have few names there. After running and modifying this How do I create a file and write to it in Java? whats inside of that file will be overwritten. I just want to add it to the new line.
Also, how can i possibly perform search?
PrintWriter out = new PrintWriter(new FileWriter("student.txt", true));
The true is the append parameter - which indicates whether the FileWriter should append to the file. If it was false it would overwrite existing data in the file.
What do you mean by "how can i possibly perform search"?
Having some issues with my program I am trying to write. Basically what I am needing to do is taking an ArrayList that I have and export the information to a text file. I have tried several different solutions from Google, but none have given me any success.
Basically I have two ArrayList, two lists, one of graduates and one of undergraduates. I simply need to take the information that is associated with these ArrayList and put them into one text file.
I'll later need to do the opposite (import) the .txt file into ArrayList, but I can figure that out later.
Any suggestions?
If you need to write the data in a specific format, you could use a PrintWriter to write the data to a file in whatever manner you wish. The problem with this is that you will then have to figure out a way in which you will then re-read the text file and populate the data.
On the other hand, you could use XStream(tutorial here) to write your files as XML. This will provide you with a human readable text file (as above) however, it will be much easier to re-read the text file when populating the data.
Lastly, you could use the ObjectOutputStream to write the data and the ObjectInputStream to re-read it back. Note however, that this method does not yield a human readable text file. Also, your classes will need to implement the Serializable interface.
Here's a solution using Apache commons-io library:
//Put all data into one big list, prepended with size of first list
List<String> allData = new ArrayList<String>(1+grads.size()+undergrads.size());
allData.add(String.valueOf(grads.size());
allData.addAll(grads);
allData.addAll(undergrads);
FileUtils.writeLines(new File("list.txt"), allData);
To read the data back:
List<String> allData = FileUtils.readLines(new File("list.txt"));
int gradsSize = Integer.parseInt(allData.get(0));
List<String> grads = allData.subList(1, gradsSize+1);
List<String> undergrads = allData.subList(1+gradsSize, allData.size());
I have a very big file (might be even 1G) that I want to create a new file from in a reversed order (in Java).
For example:
Original file:
This is the first line
This is the 2nd line
This is the 3rd line
The reversed file:
This is the 3rd line
This is the 2nd line
This is the first line
Since the file is very big, loading the entire file to memory at once and reversing the order there might be problematic (there is a limit to the memory I can use).
How can I achieve this in Java?
Thanks
Nothing very direct, I'm afraid. But you can easily create some (say) ReverseBufferedRead class wrapping a RandomAccessFile.
See also here.
Read the file by chunks of few hundreds lines, reverse the order of lines in the chunks and write them to temporary files. Then join the temporary files in the reverse order and clean up.
In other words, use disk instead of memory.
I would propose making a RandomAccessFile for the output and using setLength() to make it appropriately sized.
Then start scanning the original file and write it out in chunks starting at the end of the RandomAccessFile in reverse.
Java-ish Pseudo:
out.seek(size_of_out_file); //seek to end
RandomAccessFile out = new RandomAccessFile("out_fname", "rw");
out.setLength(size_of_file_to_be_reversed)
File in = new File ("in_fname");
while (hasMoreData(in)){
String chunk = in.readsize();
out.seekBackwardsBy(chunk.length());
out.write(chunk.reverse);
out.seekBackwardsBy(chunk.length());
}
Reading a file line-by-line in reverse order is fundamentally tricky.
It's not too bad if you've got a fixed width encoding. It's feasible if you've got a variable width encoding which you can detect the first byte of etc (e.g. UTF-8). It's virtually impossible to do efficiently if the encoding is variable width with no sensible way of determining boundaries (or if it uses "shifting" for example).
I have an implementation in C# in another question, but it would take a fair amount of effort to port that to Java.
If you use the RandomAccessFile like leonbloy suggested you can use a FileChannel
to skip to the end of the file, you can then read the line and write it to another file.
There is a simple example here in the Java tutorials: example
I would assume you know how to read a file. One way i would advise you do it is with an ArrayList of generic type string. So you read each line of the file and store it in that list. After reading you print the list out or do whatever you want to.
Just wrote something that might be of help here : http://pastebin.com/iWTVrAvm
Read using RandomAccessFile - position the file using randomAccesFile.length()and write using BufferedWriter
A better solution is use a ReversedLinesFileReader provided in Apache Commons IO package. Look at the API here https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/ReversedLinesFileReader.html