i am writing a program that read in two text files and find the differences
but for some reason, i can not print the result set. I checked for lot of times and still couldn't find the reason and i hope you guys can help me out. here is the code.
the problem occur at the for each to print the set.
import java.io.*;
import java.util.*;
public class PartOne {
public static void readFileAtPath(String filePathOne, String filePathTwo) {
// Lets make sure the file path is not empty or null
if (filePathOne == null || filePathOne.isEmpty()) {
System.out.println("Invalid File Path");
return;
}
if (filePathTwo == null || filePathTwo.isEmpty()) {
System.out.println("Invalid File Path");
return;
}
Set<String> newUser = new HashSet<String>();
Set<String> oldUser = new HashSet<String>();
BufferedReader inputStream = null;
BufferedReader inputStream2 = null;
// We need a try catch block so we can handle any potential IO errors
try {
// Try block so we can use ‘finally’ and close BufferedReader
try {
inputStream = new BufferedReader(new FileReader(filePathOne));
inputStream2 = new BufferedReader(new FileReader(filePathTwo));
String lineContent = null;
String lineContent2 = null;
// Loop will iterate over each line within the file.
// It will stop when no new lines are found.
while ((lineContent = inputStream.readLine()) != null) {
// Here we have the content of each line.
// For now, I will print the content of the line.
// System.out.println("Found the line: " + lineContent);
oldUser.add(lineContent);
}
while ((lineContent2 = inputStream.readLine()) != null) {
newUser.add(lineContent2);
}
Set<String> uniqueUsers = new HashSet<String>(newUser);
uniqueUsers.removeAll(oldUser);
}
// Make sure we close the buffered reader.
finally {
if (inputStream != null)
inputStream.close();
if (inputStream2 != null)
inputStream2.close();
}
for (String temp : uniqueUsers) {
System.out.println(temp);
}
} catch (IOException e) {
e.printStackTrace();
}
}// end of method
public static void main(String[] args) {
String filePath2 = "userListNew.txt";
String filePath = "userListOld.txt";
readFileAtPath(filePath, filePath2);
}
}
Your problem is scope. You define the set inside your try block but then you attempt to access it from outside that block. You must define all variables within the same scope you want to use that variable.
Move the definition of uniqueUsers to before your try block.
*Edit in response to your comment.
You are reading from the same input stream twice. The second while loop should be reading from inputStream2.
Try this
try {
// Try block so we can use ‘finally’ and close BufferedReader
try {
inputStream = new BufferedReader(new FileReader(filePathOne));
inputStream2 = new BufferedReader(new FileReader(filePathTwo));
String lineContent = null;
String lineContent2 = null;
// Loop will iterate over each line within the file.
// It will stop when no new lines are found.
while ((lineContent = inputStream.readLine()) != null) {
// Here we have the content of each line.
// For now, I will print the content of the line.
// System.out.println("Found the line: " + lineContent);
oldUser.add(lineContent);
}
while ((lineContent2 = inputStream.readLine()) != null) {
newUser.add(lineContent2);
}
Set<String> uniqueUsers = new HashSet<String>(newUser);
uniqueUsers.removeAll(oldUser);
for (String temp : uniqueUsers) {
System.out.println(temp);
}
}
// Make sure we close the buffered reader.
finally {
if (inputStream != null)
inputStream.close();
if (inputStream2 != null)
inputStream2.close();
}
} catch (IOException e) {
e.printStackTrace();
}
Related
i have a question about java read and write files. In the file i want to read there are four titles "this_is_table_med", "this_is_table_nts", "this_is_table_lehramt", "this_is_table_allg" which are followed by their contents. as in the picture:
I would like to split them into 4 tables as there are acutually 4 tables with titles and contents. At the end i only get the table for "this_is_table_med" and "this_is_table_lehramt", not all 4 tables, can some one help?
My codes are like:
File file = new File(inputFileName);
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
if (st != null && st.equals("this_is_table_nts")) {
File file_nts = new File(outputPath + "_nts_dropOut.csv");
FileOutputStream fo_nts = new FileOutputStream(file_nts);
BufferedWriter writer_nts = new BufferedWriter(new OutputStreamWriter(fo_nts));
st = br.readLine();
while (st != null && !st.contains("this_is_table_")) {
writer_nts.write(st);
writer_nts.newLine();
st = br.readLine();
}
writer_nts.flush();
writer_nts.close();
} else if (st != null && st.equals("this_is_table_med")) {
System.out.println(" " + st.toString());
File file_medizin = new File(outputPath + "_medizin_dropOut.csv");
FileOutputStream fo_medizin = new FileOutputStream(file_medizin);
BufferedWriter writer_medizin = new BufferedWriter(new OutputStreamWriter(fo_medizin));
st = br.readLine();
while (st != null && !st.contains("this_is_table_")) {
writer_medizin.write(st);
writer_medizin.newLine();
st = br.readLine();
}
writer_medizin.flush();
writer_medizin.close();
} else if (st != null && st.equals("this_is_table_allg")) {
System.out.println(" " + st.toString());
File file_allg = new File(outputPath + "_allg_dropOut.csv");
FileOutputStream fo_allg = new FileOutputStream(file_allg);
BufferedWriter writer_allg = new BufferedWriter(new OutputStreamWriter(fo_allg));
st = br.readLine();
while (st != null && !st.contains("this_is_table_")) {
writer_allg.write(st);
writer_allg.newLine();
st = br.readLine();
}
writer_allg.flush();
writer_allg.close();
} else if (st != null && st.equals("this_is_table_lehramt")) {
System.out.println(" " + st.toString());
File file_lehramt = new File(outputPath + "_lehramt_dropOut.csv");
FileOutputStream fo_lehramt = new FileOutputStream(file_lehramt);
BufferedWriter writer_lehramt = new BufferedWriter(new OutputStreamWriter(fo_lehramt));
st = br.readLine();
while (st != null && !st.contains("this_is_table_")) {
writer_lehramt.write(st);
writer_lehramt.newLine();
st = br.readLine();
}
writer_lehramt.flush();
writer_lehramt.close();
}
br.close();
}
Updates: i think the reason it jump over nts and allg is that: after the while-loop in the if loop for med (else if(st!=null&&st.equals("this_is_table_medizin")) "st" is equals to "this_is_table_nts". In the next step it comes to the outer while-loop "st" is the next line of "this_is_table_nts", what i need is to have st="this_is_table_nts" such that it comes to the if loop for nts.
If you are using java 8 or higher, which I strongly assume you are, and the task here was not intended to get you to deal with BufferedReader & BufferedWriter, then I would recommend a different approach, which uses Streams and java.nio.Files. This way you can easily call methods for reading and writing and only have to worry about the grouping of your lines. Grouping is also easier thanks to streams. For this I use AtomicInteger, which I increment as soon as a line starts with "this_is_table".
Assuming your inputfile is something like:
this_is_table_med
V7_1,0.0,0.0,13.79
V7_TE,0.0,0.0,100
this_is_table_nts
V8_1,0.0,0.0,13.79
V8_1,0.0,0.0,100
this_is_table_lehramt
V38_1,0.0,0.0,100
V38_TE,0.0,0.0,100
this_is_table_allg
V8_2,0.0,0.0,13.79
V8_2,0.0,0.0,13.79
and is located at fileName the folowing snippet will create 4 files (allg_dropOut.csv, lehramt _dropOut.csv, med _dropOut.csv, nts _dropOut.csv) in the outputPath directory
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Example {
public static void main(String[] args) {
AtomicInteger counter = new AtomicInteger();
String fileName = "C:\\Users\\Miaomiao\\Documents\\mydata.csv";
String outputPath = "C:\\Users\\Miaomiao\\Documents\\dir1\\";
String suffix = "_dropOut.csv";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.collect(
Collectors.groupingBy( line -> isStartOfNewTable(line)?
counter.incrementAndGet():
counter.get()))
.values().forEach(list -> {
String table = list.get(0);
Path path = Paths.get(outputPath +
table.substring(table.lastIndexOf('_') + 1) +
suffix);
try {
Files.write(path, list, StandardCharsets.UTF_8);
} catch (IOException ex) {
ex.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
static boolean isStartOfNewTable (String str){
return str.startsWith("this_is_table");
}
}
Few issues
You're reading mulitple lines at a time from the file. Leave the while loop alone. And this way, st = br.readLine() will never be null, so you don't need to check it
st will only equal a table name a handful of times, so you shouldn't check it everytime through the loop
Following code untested, but shows the general idea
branch the code between "this_is_table" lines and those without. Use a list to save data while you read it rather than immediately write to a file
when you find a new "this_is_table" line, then save off all previous lines (the list) to a file
File file = new File(inputFileName);
BufferedReader br = new BufferedReader(new FileReader(file));
String tableName = null;
String lastTable = null;
List<String> tableData = new ArrayList<>();
String st;
while ((st = br.readLine()) != null) {
if (st.startsWith("this_is_table_") { // found start of a table
// if previous table is known, then save it, e.g. write to a file here
// condition needed for first table in file
if (lastTable != null) {
String outputFile = tableName.substring("this_is_table".length()) + "_dropOut.csv";
File out = new File(outputPath, outputFile);
try(PrintStream ps = new PrintStream(out)) {
for (String line : tableData) {
ps.println(line);
}
} catch (Exception e) { System.err.println(e); }
// start collecting data for a new table
tableData = new ArrayList<>();
lastTable = tableName;
}
tableName = st;
} else {
if (tableName != null) {
// currently reading data for 'tableName'
tableData.add(st);
}
}
}
I'm trying to read into a csv file and placing the line into an array. But when I print the array out it is null.
Here is the code:
public static String[] readFile(String inFilename)
{
int lineTotal = getLineNum(inFilename);
if (lineTotal == 0)
{
System.out.println("The file is empty ");
}
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String[] resultArrayOne = new String[lineTotal + 1];
String line;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
int lineNum;
String[] resultArray = new String[lineTotal];
String info;
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
info = line;
System.out.println(info);
resultArray[lineNum] = info;
lineNum++;
}
fileStrm.close(); //Clean up the stream
resultArrayOne = resultArray;
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return resultArrayOne;
}
When printing out the line before placing it into the array the return is fine, but when placed into the array it become null.
edit:
Here is the full FileIO code:
public static String[] Import()
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the File Name: ");
String fileName = sc.nextLine();
int length = getLineNum(fileName);
String[] array = new String[length+1];
array = readFile(fileName);
return array; //array is just strings
}
public static int getLineNum(String inFilename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum = 0;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
lineNum++;
}
fileStrm.close(); //Clean up the stream
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return lineNum;
}
I'm not too sure how to insert a sample file but it is something like this:
SHOP1, STORE2, 45
SHOP2, SHOP1, 67
STORE6, SHOP1, 90
...
edit 2:
I added the code that uses this
String[] locationArrayOne = new String[1000];
locationArrayOne = FileIO.Import();
for (int yyy = 0; yyy < locationArrayOne.length; yyy++)
{
System.out.print(locationArray[yyy]);
}
Your code looks fine but here is how I would debug the problem:
Before lineNum++, I will print the value of resultArray[lineNum] instead of info to see if the program was able to retrieve the line and store it to the array.
Remove the initialization of String[] resultArrayOne and after fileStrm.close(), use resultArrayOne = resultArray.clone() to copy the values of resultArray to resultArrayOne. Copying an array by assignment (array1 = array2) could have side-effects you do not want in your program since you are making both arrays refer to the same object. Check this related question here
Also, why not use resultArrayOne directly when storing the lines?
ive gotten this far, but this doesnt work to read in the file, thats the part im stuck on. i know that you need to use the scanner, but im not sure what im missing here. i think it needs a path to the file also, but i dont know where to put that in
public class string
{
public static String getInput(Scanner in) throws IOException
{
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter file");
String filename =keyboard.next();
File inputFile = new File(filename);
Scanner input = new Scanner(inputFile);
String line;
while (input.hasNext())
{
line= input.nextLine();
System.out.println(line);
}
input.close();
}
if(filename.isEmpty())
{
System.out.println("Sorry, there has been an error. You must enter a string! (A string is some characters put together.) Try Again Below.");
return getInput(in);
}
else
{
return filename;
}
}
public static int getWordCount(String input)
{
String[] result = input.split(" ");
return result.length;
}
public static void main(String[] args)
{
DecimalFormat formatter = new DecimalFormat("0.##");
String input = getInput(new Scanner(System.in));
float counter = getWordCount(input);
System.out.println("The number of words in this string ("+input+") are: " + counter);
Scanner keyboard= new Scanner(System.in);
}
}
//end of code
First of all, when doing file I/O in Java, you should properly handle all exceptions and errors that can occur.
In general, you need to open streams and resources in a try block, catch all exceptions that happen in a catch block and then close all resources in a finally block. You should read up more on these here as well.
For using a Scanner object, this would look something like:
String token = null;
File file = null;
Scanner in = null;
try {
file = new File("/path/to/file.txt");
in = new Scanner(file);
while(in.hasNext()) {
token = in.next();
// ...
}
} catch (FileNotFoundException e) {
// if File with that pathname doesn't exist
e.printStackTrace();
} finally {
if(in != null) { // pay attention to NullPointerException possibility here
in.close();
}
}
You can also use a BufferedReader to read a file line by line.
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// ...
}
With added exception handling:
String line = null;
FileReader fReader = null;
BufferedReader bReader = null;
try {
fReader = new FileReader("/path/to/file.txt");
bReader = new BufferedReader(fReader);
while ((line = bReader.readLine()) != null) {
// ...
}
} catch (FileNotFoundException e) {
// Missing file for the FileReader
e.printStackTrace();
} catch (IOException e) {
// I/O Exception for the BufferedReader
e.printStackTrace();
} finally {
if(fReader != null) { // pay attention to NullPointerException possibility here
try {
fReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bReader != null) { // pay attention to NullPointerException possibility here
try {
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In general, use the Scanner for parsing a file, and use the BufferedReader for reading the file line by line.
There are other more advanced ways to perform reading/writing operations in Java. Check out some of them here
I want to read the 2nd line of text from a file and have that put into an array. I already have it working on the first line.
[ Code removed as requested ]
The while loop above shows how I read and save the 1st line of the text file into an array. I wish to repeat this process from the 2nd line only into a different array.
File Content:
Sofa,Armchair,Computer Desk,Coffee Table,TV Stand,Cushion,Bed,Mattress,Duvet,Pillow
599.99,229.99,129.99,40.00,37.00,08.00,145.00,299.99,24.99,09.99
Just get rid of the first readLine() call, and move the String.split() call into the loop.
Simply use the BufferedReader class to read the entire file and then manipulate the String output.
Something along these lines
public static String readFile(String fileName) throws IOException {
String toReturn = "";
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("test.txt"));
while ((sCurrentLine = br.readLine()) != null) {
toReturn = toReturn+"\n"+sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return toReturn;
}
would yield a String which can then be easily used.
public static void main(String[] args)
{
String filePath = args[0];
String[] lineElements = getLine(filePath,2).split(",");
}
public static String getLine(String path,int line)
{
List<String> cases = new ArrayList<String>();
try{
BufferedReader br = new BufferedReader(new FileReader(path));
String currLine = "";
while((currLine = br.readLine()) != null){
cases.add(currLine);
}
}catch(IOException ex){
ex.printStackTrace();
}
return cases.get(line - 1);//2nd line
}
so i am new to java.please offer some sample codes if possible.
The situation is i have a html format in a text file. i need to read the file and find the string after a pattern which is 'data-name'. i need to find every string after the "data-name" through the entire text file. i did some research online . i already used html parser to get the html and store it in a text file. i know i might need to use regular expression. so please help me. Thank you guys!
below is my code for getting the html. the result is concatenated.
public static void main(String[] args) {
try {
URL url = new URL("https://twitter.com/search?q=%23JENOSMROOKIESOPENFOLBACK&src=tren");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
PrintWriter out = new PrintWriter(new FileWriter("C:/Users/Desktop/htmlsourcecode.txt"));
while ((line = in.readLine()) != null) {
System.out.println(line);
out.print(line);
}
out.close();
}
How about something like this
// External resource(s).
BufferedReader in = null;
PrintWriter out = null;
try {
URL url = new URL(
"https://twitter.com/search?q=%23JENOSMROOKIESOPENFOLBACK&src=tren");
// read text returned by server
in = new BufferedReader(new InputStreamReader(
url.openStream()));
String line;
// out = new PrintWriter(new FileWriter(
// "htmlsourcecode.txt"));
final String DATA_NAME = "data-name=\"";
while ((line = in.readLine()) != null) {
int pos1 = line.indexOf(DATA_NAME); // opening position.
if (pos1 > -1) { // did we match?
// Add the length of the string.
pos1 += DATA_NAME.length();
// find the closing quote.
int pos2 = line.indexOf("\"", pos1 + 1);
if (pos2 > -1) {
String dataName = line.substring(pos1,
pos2);
System.out.println(dataName);
// out.print(line);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close external resource(s).
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
out.close();
}
}