How to read file until a specific element - java

I'm facing a problem that I can't (more likely I don't know how to) read a file until a specific element.
My file looks like:
Vaga
Senieji Amatai, 2016, 5,4
Humanitas
Kolumbas, 1980, 3
Programavimas Java, 2016, 14,56
And any ideas how to stop it reading at 5,4?
Here's a little part of my code:
File FILE = new File(duomenuFailas);
if (FILE.exists() && FILE.length() > 0) {
try {
Scanner SC = new Scanner(FILE);
for (int i = 0; i < FILE.length(); i++) {
if (SC.hasNextLine()) {
String[] parodyti = SC.nextLine().split(",");
System.out.println(parodyti[0]);
}
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}

Try something like that:
File file = new File(duomenuFailas);
if (file.isFile()) {
try {
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String[] parodyti = sc.nextLine().split(",");
System.out.println(parodyti[0]);
if (parodyti[0].equals(stopElement)) {
break;
}
}
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}

Related

Create text file dynamically in a specified directory, write data,read data from that file in java

Recently i have tried to write code of above given title and the problem is that i could not get sufficient date to write upon have a look at my code .it is showing some errors like
it is showing invalid token for semicolon after tagfile.createnewfile();
let us look at code:
public class WriteToFileExample {
String path = "G:"+File.separator+"Software"+File.separator+"Files";
String fname= path+File.separator+"fileName.txt";
boolean bool=false;
File f = new File(path);
File f1 = new File(fname);
try {
f1.createNewFile();
bool=f.mkdirs() ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static final String FILENAME = "G:\\Software\\Files\\anil.txt";
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String content = null;
String[] str = new String[100];
try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) {
System.out.println(" enter no.of line to be inserted into file");
int k = sc.nextInt();
for (int i = 0; i <= k; i++) {
System.out.println(" enter " + i + " line data");
content = sc.nextLine();
bw.write(content);
str[i] = content;
}
System.out.println("The content present in\n
G:\Software\Files\anil.txt is:");
for (int i = 1; i <= k; i++)
System.out.println(str[i]);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please find the code and then you can use
**Writing** : PrintWriter,Scanner,BufferedWriter etc to write to that file
**Reading** :FileReader,BufferReader,Scanner with these readers etc
String path = "G:"+File.separator+"Software"+File.separator+"Files";
String fname= path+File.separator+"fileName.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Ref : https://www.lynda.com/Java-tutorials/Reading-writing-text-files/107061/113497-4.html
Refer above video which may help

Application not writing file

As a beginner, I am trying to print a set of info to a file called "Sign_in.txt" but this code only creates the file and doesn't print anything. What am I doing wrong?
String nu="CUSTOMER DETAILS START";
String enu="CUSTOMER DETAILS END";
n=namefield.getText();
a=agefield.getText();
ad=adfield.getText();
s=salfield.getText();
p=phfield.getText();
d=dobfield.getText();
e=emfield.getText();
ArrayList<String> list = new ArrayList<String>();
list.add(nu);
list.add(n);
list.add(a);
list.add(ad);
list.add(s);
list.add(p);
list.add(d);
list.add(e);
list.add(u);
list.add(q);
list.add(enu);
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Sign_in.txt",true)))) {
Writer output = new BufferedWriter(out);
int l = list.size();
for(int i = 0; i<l; i++){
output.write(list.get(i).toString()+"\n");
}
output.close();
}
catch (Exception e)
{
e.printStackTrace();
}
JOptionPane.showMessageDialog(this,"Thank you for registering");
System.exit(0);
new accpage().setVisible(true);
}
I would have something like this:
try (PrintWriter output =
new PrintWriter(new BufferedWriter(new FileWriter("Sign_in.txt"))))
{
for (String line: list) {
output.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Working code
try (PrintWriter output = new PrintWriter(
new BufferedOutputStream(
new FileOutputStream("Sign_in.txt")), true))
{
int l = list.size();
for (int i = 0; i < l; i++) {
output.println(list.get(i).toString());
}
} catch (Exception e) {
e.printStackTrace();
}

how to make the users appear once while reading a csv file?

I have a program I wrote that can read a csv file. The csv file have two columns one for clusters number and the other is for users. what I need for the program is not to repeat the user. Instead, to write the user once and in each cluster to simply write 1 if the user had shown in that cluster number.
package parsing;
public static void main(String[]args){
String fileName= "ClusterResult(final1).csv";//reading the file
File file = new File(fileName);
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()){
String data = inputStream.next();
String [] myArray= data.split(",");
for(int i =0; i<=27;i++){// because I have 27 clusters
Arrays.sort(myArray);
int founditem= Arrays.binarySearch(myArray, String.valueOf(i));
if (founditem>-1 )
System.out.print("1"); //if the user name showed in the cluster the user should have one next to the cluster number
else
System.out.print("0");
}
System.out.println();
System.out.println(myArray[1] );
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
the output of the program is :
1000000000000000000000000000
ElDaddy
1000000000000000000000000000
Lxve
1000000000000000000000000000
Lxve
0000001000000000000000000000
ElDaddy
where it should be for example :
1000001000011000010100000000
ElDaddy
You say in your question your csv has two columns, if that's true, try something like this:
public static void main(String[] args) {
HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
String fileName = "ClusterResult(final1).csv";// reading the file
FileReader file = null;
try {
file = new FileReader(new File(fileName));
} catch (FileNotFoundException e1) {
System.err.println("File " + fileName + " not found!");
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(file);
String line;
try {
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
generateClusters(data[0], data[1], map);
}
for (Entry<String, HashSet<String>> entry : map.entrySet()) {
for (int i = 0; i < 27; i++) {
if (entry.getValue().contains(String.valueOf(i)))
System.out.print(1);
else
System.out.print(0);
}
System.out.println();
System.out.println(entry.getKey());
}
} catch (IOException e) {
System.err.println("Error when reading");
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
}
}
public static void generateClusters(String e1, String e2,
HashMap<String, HashSet<String>> map) {
HashSet<String> clustersOfUser = map.get(e1);
if (clustersOfUser == null) {
clustersOfUser = new HashSet<String>();
map.put(e1,clustersOfUser);
}
clustersOfUser.add(e2);
}
What we are doing here is grouping the users in a HashMap, but storing the clusters
as keys.

Merge Two text files line by line using java

First text file
A.txt;
asdfghjklqw12345 qwe3456789
asdfghjklqw12345 qwe3456789
Second text file
B.txt;
|Record 1: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
|Record 2: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
Third text file
C.txt;
asdfghjklqw12345 qwe3456789 |Record 1: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
asdfghjklqw12345 qwe3456789 |Record 2: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
for the above situation where I want to merge two lines from two different text files into one line.My code is below
List<FileInputStream> inputs = new ArrayList<FileInputStream>();
File file1 = new File("C:/Users/dell/Desktop/Test/input1.txt");
File file2 = new File("C:/Users/dell/Desktop/Test/Test.txt");
FileInputStream fis1;
FileInputStream fis2;
try {
fis1 = new FileInputStream(file1);
fis2= new FileInputStream(file2);
inputs.add(fis1);
inputs.add(fis2);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int total = (int) (file1.length() + file2.length());
System.out.println("total length is " + total);
SequenceInputStream sis = new SequenceInputStream(Collections.enumeration(inputs));
try {
System.out.println("SequenceInputStream.available() = "+ sis.available());
byte[] merge = new byte[total];
int soFar = 0;
do {
soFar += sis.read(merge,total - soFar, soFar);
} while (soFar != total);
DataOutputStream dos = new DataOutputStream(new FileOutputStream("C:/Users/dell/Desktop/Test/C.txt"));
soFar = 0;
dos.write(merge, 0, merge.length);
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here is code:
public class MergeText {
public static void main(String[] args) throws IOException{
String output="";
try(Scanner sc1=new Scanner((new File("A.txt")));
Scanner sc2=new Scanner((new File("B.txt")))){
while(sc1.hasNext() || sc2.hasNext()){
output+=sc1.next() +" "+ sc2.next();
output+="\n";
}
}
try(PrintWriter pw=new PrintWriter(new File("C.txt"))){
pw.write(output);
}
}
}
You might want to have a look at BufferedReader and BufferedWriter.
Show us what you tried and where you are stuck and we are happy to provide more help.
Merging all txt file from a folder can be done in the following way:
public static void main(String[] args) throws IOException {
ArrayList<String> list = new ArrayList<String>();
//Reading data files
try {
File folder = new File("path/inputFolder");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
BufferedReader t = new BufferedReader (new FileReader (file));
String s = null;
while ((s = t.readLine()) != null) {
list.add(s);
}
t.close();
}
}
}
catch (IOException e) {
e.printStackTrace();
}
//Writing merged data file
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("data.output/merged-output.txt"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("\n");
}
System.out.println("complited");
writer.flush();
writer.close();
}
Improved on Masudul's answer to avoid compilation errors:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class MergeText {
public static void main(String[] args) throws IOException {
StringBuilder output = new StringBuilder();
try (Scanner sc1 = new Scanner((new File("C:\\Users\\YourName\\Desktop\\A.txt")));
Scanner sc2 = new Scanner((new File("C:\\Users\\YourName\\Desktop\\B.txt")))) {
while (sc1.hasNext() || sc2.hasNext()) {
String s1 = (sc1.hasNext() ? sc1.next() : "");
String s2 = (sc2.hasNext() ? sc2.next() : "");
output.append(s1).append(" ").append(s2);
output.append("\n");
}
}
try (PrintWriter pw = new PrintWriter(new File("C:\\Users\\mathe\\Desktop\\Fielddata\\RESULT.txt"))) {
pw.write(output.toString());
}
}
}

Why won't the catch block run?

I have the following method to write an array to a text file. If a existing text file is given then it works fine but if a file that doesn't exist is given neither try-catch will run the code to restart the method. I'm not given any error or anything but the catch block won't run. I didn't think i would need to catch for an IOException but the code won't even run if i don't do that. So yea, anyone know how i can get this to work?
Edit: Forgot to mention the getInput method prompts the user for input.
private static void openFileWriter(String prompt, boolean append, int wordsperline, String[] story) {
try {
try {
save = new PrintWriter(new FileWriter(getInput(prompt), append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for (int x = 0; x <= story.length-1; x++) {
if (story[x] == null) {
} else {
if (wordsperline == 21) {
save.println(story[x]);
wordsperline = 0;
} else {
save.print(story[x]);
wordsperline++;
}
}
}
save.close();
} catch (FileNotFoundException e1) {
openFileWriter("File not found", append,wordsperline,story);
}
} catch (IOException e) {
// TODO Auto-generated catch block
openFileWriter("File not found", append,wordsperline,story);
}
}
If the File does not exist you cannot write to it, in your catch block you are trying to write the error to the File that doesn't exist. Also, I think you only need 1 catch block here, and note that one of the if statement blocks is empty.
try this:
try
{
save = new PrintWriter(new FileWriter(getInput(prompt), append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for(int x = 0; x <= story.length-1; x++)
{
if (story[x] == null)
{
}
else
{
if (wordsperline == 21)
{
save.println(story[x]);
wordsperline = 0;
}
else
{
save.print(story[x]);
wordsperline++;
}
}
}
save.close();
}
catch (FileNotFoundException e1)
{
System.err.println(e1.getMessage());
}
catch (IOException e)
{
System.err.println(e.getMessage());
}
See FileWriter javadoc.
Quoting from the constructor doc:
Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
If you pass it a filename that doesn't exist, but is a legal filename in a location where you have permission to write, it simply creates the file.
Your code in fact does reach the catch blocks if you pass it a directory (somewhat oddly, it catches a FileNotFoundException in this situation for me rather than the documented IOException).
To check if a file exists, see File javadoc
Try this version and send the stack trace when you get the exception:
public static List<String> splitByLength(String filename, int length) {
List<String> splitWords = new ArrayList<String>();
for (int i = 0; i < str.length(); i += length) {
splitWords
.add(str.substring(i, Math.min(str.length(), i + length)));
}
return splitWords;
}
private static void openFileWriter(String prompt, boolean append,
int wordsperline, String[] story) {
PrintWriter save = null;
try {
save = new PrintWriter(new FileWriter("c:\\test.txt", append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for (int x = 0; x <= story.length - 1; x++) {
if (story[x] != null) {
List<String> splitWords = splitByLength(story[x], 21);
for (String line : splitWords) {
save.println(line);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (save != null) {
save.close();
}
}
}

Categories

Resources