How can I print out a shuffled ArrayList? - java

How can I print out a shuffled ArrayList? This is what I have so far:
public class RandomListSelection {
public static void main(String[] args) {
String currentDir = System.getProperty("user.dir");
String fileName = currentDir + "\\src\\list.txt";
// Create a BufferedReader from a FileReader.
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(
fileName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Create ArrayList to hold line values
ArrayList<String> elements = new ArrayList<String>();
// Loop over lines in the file and add them to an ArrayList
while (true) {
String line = null;
try {
line = reader.readLine();
// Add each line to the ArrayList
elements.add(line);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (line == null) {
break;
}
}
// Randomize ArrayList
Collections.shuffle(elements);
// Print out shuffled ArrayList
for (String shuffedList : elements) {
System.out.println(shuffedList);
}
// Close the BufferedReader.
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

In order to remove the single null-value, you should only read (and add to the collection) as long as there are lines.
In your code, you set the string to null, your reader can't read anything else, and adds the String (which is still null) to the List. After that, you check, if the String is null and leave your loop!
Change your loop to this:
// Loop over lines in the file and add them to an ArrayList
String line="";
try{
while ((line=reader.readLine())!=null) {
elements.add(line);
}
}catch (IOException ioe){
ioe.printStackTrace();
}

Try this.
public static void main(String[] args) throws IOException {
String currentDir = System.getProperty("user.dir");
Path path = Paths.get(currentDir, "\\src\\list.txt");
List<String> list = Files.readAllLines(path);
Collections.shuffle(list);
System.out.println(list);
}

Related

Access variable in try block

I want to remove the throws FileNotFoundException from the method head and put it into it.
public static String[] read(String file) throws FileNotFoundException {
But then I can't access in (the scanner) anymore! How to handle that?
public static String[] read(String file) {
try {
Scanner in = new Scanner(new FileReader(file));
}
catch (Exception e) {
}
// ...
in.close();
// ...
}
Just use try-with-resources so you dont have to worry about closing the scanner object.
try (Scanner in = new Scanner(new FileReader(file))) {
//Your code
}
catch (Exception e) {
}
you can use try with ressource, that permit to close automaticaly your in.
like that
Scanner in ;
try ( in = new Scanner(new FileReader(file))) {
}
catch (Exception e) {
}
The variable in is out of scope outside the try block. You can either do this:
public static String[] read(String file) {
Scanner in = null;
try {
in = new Scanner(new FileReader(file));
}
catch (Exception e) {
}
finally() {
in.close();
}
// ...
}
Or better yet, try with resources
public static String[] read(String file) {
try (Scanner in = new Scanner(new FileReader(file))){
String line = in.nextLine();
// whatever comes next
}
catch (Exception e) {
}
// right here, the scanner object will be already closed
return ...;
}
The in variable is locally scoped to the try block. You can either declared the variable before the try block, or close in within the try block. There's not much use in closing it if it never successfully opened.

How to eliminate having an ArrayIndexOutOfBoundExceptions in Java?

I have a Java program that reads from a cvs file that looks like this:
2000;Mall1;8
2002;Mall3;23
2003;Mall4;31
...
I want the program to read from the cvs file into an array and sort the array based on the third column/field.
However, whenever I print the elements of array[2] I get an ArrayIndexOutOfBoundException. I can't see why is this happening since the array's[2] size should be already fixed.
Here is the code:
import java.util.*;
import java.io.*;
public class Prog3
{
public static void main(String[] args)
{
String csvFile = "test.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] array = line.split(cvsSplitBy);
System.out.println(array[2]);
Arrays.sort(array[2]);
System.out.println("Sorted\n" + Arrays.toString(array[2]));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
finally {
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Any help is appreciated :)

How to write only once to file from a thread?

I want to write something to the end of the file every time the file is modified and I'm using this code :
public class Main {
public static final String DIRECTORY_TO_WATCH = "D:\\test";
public static void main(String[] args) {
Path toWatch = Paths.get(DIRECTORY_TO_WATCH);
if (toWatch == null) {
throw new UnsupportedOperationException();
}
try {
WatchService myWatcher = toWatch.getFileSystem().newWatchService();
FileWatcher fileWatcher = new FileWatcher(myWatcher);
Thread t = new Thread(fileWatcher, "FileWatcher");
t.start();
toWatch.register(myWatcher, StandardWatchEventKinds.ENTRY_MODIFY);
t.join();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and the thread class :
public class FileWatcher implements Runnable{
private WatchService myWatcher;
private Path toWatch;
String content = "Dong\n";
int counter = 0;
public FileWatcher (WatchService myWatcher, Path toWatch) {
this.myWatcher = myWatcher;
this.toWatch = toWatch;
}
#Override
public void run() {
try {
WatchKey key = myWatcher.take();
while (key != null) {
for (WatchEvent event : key.pollEvents()) {
//System.out.printf("Received %s event for file: %s\n", event.kind(), event.context());
//System.out.println(counter);
myWatcher = null;
File file = new File(Main.DIRECTORY_TO_WATCH + "\\" + event.context());
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
fw.write(counter + content);
fw.close();
counter++;
myWatcher = toWatch.getFileSystem().newWatchService();
toWatch.register(myWatcher, StandardWatchEventKinds.ENTRY_MODIFY);
// BufferedWriter bwWriter = new BufferedWriter(fw);
// bwWriter.write(content);
// bwWriter.close();
}
key.reset();
key = myWatcher.take();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I want to get in the file something like :
acasc 0dong
dwqcacesv 1dong
terert 2dong
However, now I'm getting this, because it writes too many times in the file:
acasc 0dong
1dong
...
50123dong
If I use System.out.println(counter); it works as I want to (prints the number of file changes correctly), but it goes wild on fw.write(counter + content);
Your thread's write is causing further changes to the file.
Self feeding loop.

Getting error while trying to close text writer

This is my first attempt at file writing to save data in a java program, and i found this solution here on SO, but i am getting an error in my finally statement when i try to close the PrintWriter, saying "out cannot be resolved".
Much thanks.
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class MedConcept {
public static void main(String[] args) {
ConsoleReader console = new ConsoleReader(System.in);
try {
PrintWriter out = new PrintWriter("med.txt");
System.out.println("Name of the medication:");
String medName = console.readLine();
System.out.println("The Dosage of the medication:");
Double medDose = console.readDouble();
System.out.println("Time of day to take");
String dayTime = console.readLine();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
out.close();
}
}
}
The variable out is declared inside the try block which is not visible in the finally block. Move the declaration outside and add a check on whether it is null when closing it.
PrintWriter out = null;
try {
out = new PrintWriter("med.txt");
System.out.println("Name of the medication:");
String medName = console.readLine();
System.out.println("The Dosage of the medication:");
Double medDose = console.readDouble();
System.out.println("Time of day to take");
String dayTime = console.readLine();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(out != null) {
out.close();
}
}
If you're using Java 7, you can avoid manually closing the PrintWriter with a try-with-resources statement.
try (PrintWriter out = new PrintWriter("med.txt")) {
...
} catch() {
...
}

How to remove a line from a file by knowing its position?

I want to remove a line from my file (specifically the second line)
so I have used another file to copy in it ,but using the following code the second file contain exactly the same text.(My original file .txt and my final file .xml)
public static File fileparse() throws SQLException, FileNotFoundException, IOException {
File f=fillfile();//my original file
dostemp = new DataOutputStream(new FileOutputStream(filetemp));
int lineremove=1;
while (f.length()!=0) {
if (lineremove<2) {
read = in.readLine();
dostemp.writeBytes(read);
lineremove++;
}
if (lineremove==2) {
lineremove++;
}
if (lineremove>2) {
read = in.readLine();
dostemp.writeBytes(read);
}
}
return filetemp;
}
You do not read the line if the lineremove is 2 and also you check if it is greater than 2 after you increased it when it was 2. Do it like this:
int line = 1;
String read = null;
while((read = in.readLine()) != null){
if(line!=2)
{
dostemp.writeBytes(read);
}
line++;
}
you can use BufferedReader with the readLine() method to read line by line, check if it a line you want and skip the lines you dont want.
check the docs at: BufferedReader
here is a working example (Not the most beautiful or clean :) ):
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("d:\\test.txt"));
} catch (FileNotFoundException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
PrintWriter out = null ;
try {
out = new PrintWriter (new FileWriter ("d:\\test_out.txt"));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String line = null;
int lineNum = 0;
try {
while( (line = in.readLine()) != null) {
lineNum +=1;
if(lineNum == 2){
continue;
}
out.println(line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out.flush();
out.close();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories