I have to write code that will reverse the order of the string and write it in a new file. For example :
Hi my name is Bob.
I am ten years old.
The reversed will be :
I am ten years old.
Hi my name is Bob.
This is what I have so far. Not sure what to write for the outWriter print statement. Any help will be appreciated. Thanks!
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class FileRewinder {
public static void main(String[] args) {
File inputFile = new File("ascii.txt");
ArrayList<String> list1 = new ArrayList<String>();
Scanner inputScanner;
try {
inputScanner = new Scanner(inputFile);
} catch (FileNotFoundException f) {
System.out.println("File not found :" + f);
return;
}
while (inputScanner.hasNextLine()) {
String curLine = inputScanner .nextLine();
System.out.println(curLine );
}
inputScanner.close();
File outputFile = new File("hi.txt");
PrintWriter outWriter = null;
try {
outWriter = new PrintWriter(outputFile);
} catch (FileNotFoundException e) {
System.out.println("File not found :" + e);
return;
}
outWriter.println(???);
outWriter.close();
}
}
My suggestion is read entire file first and store sentences(you can split by .) in a LinkedList<String>(this will keep insertion order)
Then use Iterator and get sentences in reverse order. and write them into a file. make sure to put . just after each sentence.
After System.out.println(curLine ); add list1.add(curline); that will place your lines of text into your list.
At the end create a loop over list1 backwards:
for(int i = list1.size() - 1 , i > 0, --i) {
outWriter.println(list1[i]);
}
If the file contains an amount of lines which can be loaded into the memory. You can read all lines into a list, reverse the order of the list and write the list back to the disk.
public class Reverse {
static final Charset FILE_ENCODING = StandardCharsets.UTF_8;
public static void main(String[] args) throws IOException {
List<String> inLines = Files.readAllLines(Paths.get("ascii.txt"), FILE_ENCODING);
Collections.reverse(inLines);
Files.write(Paths.get("hi.txt"), inLines, FILE_ENCODING);
}
}
Related
I am solving a problem from Advent of Code, and trying to put the content of the input file into an arraylist, here's my code for that:
ArrayList<Integer> arrayList = new ArrayList<>();
try (Scanner s = new Scanner(new File("input.txt")).useDelimiter(",")) {
while (s.hasNext()) {
int b = Integer.parseInt(s.next());
arrayList.add(b);
}
}
catch (FileNotFoundException e) {
// Handle the potential exception
}
System.out.println(arrayList);
and when I run it, it does not print the arraylist. I can't understand why, could someone tell me what I did wrong?
I used StringTokenizer and it works perfectly. I am not familiar with using Scanner to split items, so I converted it over into a StringTokenizer. Hope you're okay with that.
public static void main(String[] args) throws IOException {
ArrayList<Integer> arrayList = new ArrayList<>();
Scanner s = new Scanner(new File("input.in"));
StringTokenizer st = new StringTokenizer(s.nextLine(), ",");
while (st.hasMoreTokens()) {
int b = Integer.parseInt(st.nextToken());
arrayList.add(b);
}
s.close();
System.out.println(arrayList);
}
This fills your ArrayList with the values you want
You can validate if you are able to read the file or not. Your code can be modifed something like this. Please check if it prints "File found". If not it means that file you are trying to read is not in classpath. You might want to refer https://mkyong.com/java/java-how-to-read-a-file/
...
File source = new File("input.txt");
if(source.exists()) {
System.out.println("File found");
}
try (Scanner s = new Scanner(source).useDelimiter(",")) {
...
I'm new to Java and I have to read from a file, and then convert what I have read into variables. My file consists of a fruit, then a price and it has a long list of this. The file looks like this:
Bananas,4
Apples,5
Strawberry,8
...
Kiwi,3
So far I have created two variables(double price and String name), then set up a scanner that reads from the file.
public void read_file(){
try{
fruits = new Scanner(new File("fruits.txt"));
print_file();
}
catch(Exception e){
System.out.printf("Could not find file\n");
}
}
public void print_file(){
while(fruits.hasNextLine()){
String a = fruits.nextLine();
System.out.printf("%s\n", a);
return;
}
}
Currently I am only able to print out the entire line. But I was wondering how I could break this up to be able to store the lines into variables.
So your string a has an entire line like Apples,5. So try to split it by comma and store it into variables.
String arr[] = a.split(",");
String name = arr[0];
int number = Integer.parseInt(arr[1]);
Or if prices are not integers, then,
double number = Double.parseDouble(arr[1]);
Using java 8 stream and improved file reading capabilities you can do it as follows. it stores item and count as key value pair in a map. It is easy to access by key afterwards.
I know this Maybe too advance but eventually this will help you later when getting to know new stuff in java.
try (Stream<String> stream = Files.lines(Paths.get("src/test/resources/items.txt"))) {
Map<String, Integer> itemMap = stream.map(s -> s.split(","))
.collect(toMap(a -> a[0], a -> Integer.valueOf(a[1])));
System.out.println(itemMap);
} catch (IOException e) {
e.printStackTrace();
}
output
{Apples=5, Kiwi=3, Bananas=4, Strawberry=8}
You can specify a delimiter for the scanner by calling the useDelimiter method, like:
public static void main(String[] args) {
String str = "Bananas,4\n" + "Apples,5\n" + "Strawberry,8\n";
try (Scanner sc = new Scanner(str).useDelimiter(",|\n")) {
while (sc.hasNext()) {
String fruit = sc.next();
int price = sc.nextInt();
System.out.printf("%s,%d\n", fruit, price);
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"C://Test/myfile.txt")); //Your file location
String line = reader.readLine(); //reading the line
while(line!=null){
if(line!=null && line.contains(",")){
String[] data = line.split(",");
System.out.println("Fruit:: "+data[0]+" Count:: "+Integer.parseInt(data[1]));
}
//going over to next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm designing a program to split data stored in a text file into two separate files based on the label of that data.
Here is a small version of that data.
0,1,2,normal.
5,5,5,strange.
2,1,3,normal.
I use a class to store each line as a sample. The class parses the line to store the last value as the label. I encapsulated each line as an object, because I intend to add features later.
Here is code for the Sample class
import java.util.Scanner;
public class Sample {
String[]str_vals = new String[3];
String label;
Sample(Scanner line) {
for (int i=0; i<3; i++) {
str_vals[i] = line.next();
}
label = line.next();
}
String getValsForCSV() {
StringBuilder retval = new StringBuilder();
for (int i=0; i<3; i++) {
retval.append(str_vals[i]).append(",");
}
retval.append(label).append(".");
return retval+"";
}
String getLabel() {
return label;
}
}
Below is the code in question. My Separator class.
import java.io.*;
import java.util.Scanner;
public class Separator {
public static final String DATAFILE = "src/etc/test.txt";
public static void main(String[] args) throws FileNotFoundException {
runData();
}
public static void runData() throws FileNotFoundException {
try (Scanner in = new Scanner(new File(DATAFILE))) {
// kddcup file uses '.\n' at end of each line
// setting this as delimiter which will consume the period
in.useDelimiter("[.]\r\n|[.]\n|\n");
Sample curr;
while(in.hasNext()) {
// line will hold all fields for a single sample
Scanner line = new Scanner(in.next());
line.useDelimiter(", *");
curr = new Sample(line);
try (
PrintWriter positive = new PrintWriter(new File(DATAFILE+"-pos"));
PrintWriter negative = new PrintWriter(new File(DATAFILE+"-neg"));
) {
if (curr.getLabel().equals("normal")) {
positive.println("GOOD");
} else {
negative.println("BAD");
}
}
}
}
}
}
This issue that I am experiencing is that the code only saves the last Sample seen to its respective file. So with above data the test.txt-neg will be empty and test.txt-pos will have a single line GOOD; it does not have two GOOD's as expected.
If I modify the test.txt data to include only the first two lines, then the files states are reversed (i.e. test.txt-neg has BAD and test.txt-pos is empty). Could someone please explain to me what is going on, and how to fix this error?
Because the error was pointed out in a comment. I wanted to give credit to KevinO and Elliott Frisch for the solution.
As mentioned, I'm creating a new PrintWriter each time and creating the PrintWriter in it's default mode of overwriting a file. As a result it always saves both files based on a single sample.
To correct this error, I have pulled out the instantiations of the PrintWriter to be in the try-with-resource block of the Scanner object
import java.io.*;
import java.util.Scanner;
public class Separator {
public static final String DATAFILE = "src/etc/test.txt";
public static void main(String[] args) throws FileNotFoundException {
runData();
}
public static void runData() throws FileNotFoundException {
try (
Scanner in = new Scanner(new File(DATAFILE));
PrintWriter positive = new PrintWriter(new File(DATAFILE+"-pos"));
PrintWriter negative = new PrintWriter(new File(DATAFILE+"-neg"));
) {
// kddcup file uses '.\n' at end of each line
// setting this as delimiter which will consume the period
in.useDelimiter("[.]\r\n|[.]\n|\n");
Sample curr;
while(in.hasNext()) {
// line will hold all fields for a single sample
Scanner line = new Scanner(in.next());
line.useDelimiter(", *");
curr = new Sample(line);
if (curr.getLabel().equals("normal")) {
positive.println("GOOD");
} else {
negative.println("BAD");
}
}
}
}
}
I want to be able to remove blank lines from a text file, for example:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
--To This:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
All of the code I have is below:
public class Driver {
public static void main(String[] args)
throws Exception {
Scanner file = new Scanner(new File("src/data.txt"));
PrintWriter write = new PrintWriter("src/data.txt");
while(file.hasNext()) {
if (file.next().equals("")) {
continue;
} else {
write.write(file.next());
}
}
print.close();
file.close();
}
}
The problem is that the text file is empty once I go back and look at the file again.
Im not sure why this is acting this way since they all seem to be blank characters, \n showing line breaks
Your code was almost correct, but there were a few bugs:
You must use .nextLine() instead of .next()
You must write to a different file while reading the original one
Your print.close(); should be write.close();
You forgot to add a new line after each line written
You don't need the continue; instruction, since it's redundant.
public static void main(String[] args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File("src/data.txt"));
writer = new PrintWriter("src/data2.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you want to keep the original name, you can do something like:
File file1 = new File("src/data.txt");
File file2 = new File("src/data2.txt");
file1.delete();
file2.renameTo(file1);
Try org.apache.commons.io and Iterator
try
{
String name = "src/data.txt";
List<String> lines = FileUtils.readLines(new File(name));
Iterator<String> i = lines.iterator();
while (i.hasNext())
{
String line = i.next();
if (line.trim().isEmpty())
i.remove();
}
FileUtils.writeLines(new File(name), lines);
}
catch (IOException e)
{
e.printStackTrace();
}
You could copy to a temporary file and rename it.
String name = "src/data.txt";
try(BufferedWriter bw = new BufferedWriter(name+".tmp)) {
Files.lines(Paths.get(name))
.filter(v -> !v.trim().isEmpty())
.forEach(bw::println);
}
new File(name+".tmp").renameTo(new File(name));
This piece of code solved this problem for me
package linedeleter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class LineDeleter {
public static void main(String[] args) throws FileNotFoundException, IOException {
File oldFile = new File("src/data.txt"); //Declares file variable for location of file
Scanner deleter = new Scanner(oldFile); //Delcares scanner to read file
String nonBlankData = ""; //Empty string to store nonblankdata
while (deleter.hasNextLine()) { //while there are still lines to be read
String currentLine = deleter.nextLine(); //Scanner gets the currentline, stories it as a string
if (!currentLine.isBlank()) { //If the line isn't blank
nonBlankData += currentLine + System.lineSeparator(); //adds it to nonblankdata
}
}
PrintWriter writer = new PrintWriter(new FileWriter("src/data.txt"));
//PrintWriter and FileWriter are declared,
//this part of the code is when the updated file is made,
//so it should always be at the end when the other parts of the
//program have finished reading the file
writer.print(nonBlankData); //print the nonBlankData to the file
writer.close(); //Close the writer
}
}
As mentioned in the comments, of the code block, your sample had the print writer declared after your scanner meaning that the program had already overwritten your current file of the same name. Therefore there was no code for your scanner to read and thus, the program gave you a blank file
the
System.lineSeparator()
Just adds an extra space, this doesn't stop the program from continuing to write on that space, however, so it's all good
I just started to code a while back and I'm in the process of dealing with arrays on my own, I understand them in theory but I need some help when it comes to getting practical. I asked my instructor to give me a couple of practices problems and he gave me the following.
using this as your main:
public static void main(String[] args) {
DatosPalabras datos = new DatosPalabras( "words.txt" );
JOptionPane.showMessageDialog(null, datos );
datos.sort();
JOptionPane.showMessageDialog(null, datos);
}
(its in spanish so bear with me) create a class named DatosPalabras and words.txt and make sure your code can:
Read and display words.txt
Display the words in "words.txt" in alphabetical order
I really appreciate the help, I'm a bit stumped but I'm curious to know how I can accomplish this. Thank you!
EDIT:
public class DatosPalabras {
public DatosPalabras(String string) {
// read and display the content of words.txt
}
public void sort() {
// need info on what to use in order to sort words instead of doubles and integers.
}
}
In this example I have 1 file named Q19505617.java. Java only allows you to have 1 public class per file. It is the class that defines the main method. So this example works only because the DatosPalabras class is contained in that file. If you need DatosPalabras to be its own class then put the DatosPalabras in its own file named DatosPalabras.java and change the class signature to be public class DatosPalabras.
import java.io.InputStream;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Q19505617 {
public static void main(String[] args) {
DatosPalabras datos = new DatosPalabras("words.txt");
JOptionPane.showMessageDialog(null, datos);
datos.sort();
JOptionPane.showMessageDialog(null, datos);
}
}
class DatosPalabras {
private String[] lines;
public DatosPalabras(String filename) {
lines = new String[1];
int lineCounter = 0;
InputStream in = Q19505617.class.getResourceAsStream(filename);
Scanner scanner = new Scanner(in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
if(lineCounter == lines.length) {
lines = Arrays.copyOf(lines, lines.length * 2);
}
lines[lineCounter] = line;
lineCounter++;
}
}
public void sort() {
// put your real sort algorithm here. until then use this:
}
public String toString() {
StringBuilder b = new StringBuilder();
for (String line : lines) {
b.append(line).append("\n");
}
return b.toString();
}
}
You can create a reading Array like this:
String[] Array = new String[number of lines in you txt file];
int i = 0;
// Selecting the txt file
File theFile = new File("bla.txt");
//Creating a scanner to read the file
scan = new Scanner(theFile);
//Reading all the words from the txt file
while (scan.hasNextLine()) {
line = scan.nextLine();
Array[i] = line; // gets all the lines
i++;
Then you create a method for sorting.